【问题标题】:Appending n number of strings from json object together efficiently?有效地将来自json对象的n个字符串附加在一起?
【发布时间】:2017-04-23 21:48:39
【问题描述】:

所以我有一个像这样的 json 对象:

data = [{key1: 123, key2:"this is the first string to concatenate"},
 {key1: 131, key2:"C'est la deuxième chaîne à concaténer"},
 {key1: 152, key2:"this is the third string to concatenate"},
 {key1: 152, key2:"this is the fourth string to concatenate"} ] 

我想将所有英文key2 字符串连接在一起,例如:

"this is the first string to concatenate this is the third string to concatenate this is the fourth string to concatenate" 

基于this 的问题,我正在这样做:

all_key2 = " ".join([elem["key2"] for elem in data if langid.classify(elem["key2"])=="english"])

但是,是否可以限制加入列表的项目数量?例如,如果我只想连接最多 2 个英语 key2's 怎么办?这意味着我想要这样的东西:

"this is the first string to concatenate this is the third string to concatenate" 

基本上,一旦我连接了最大数量的英文句子,我就不想再连接了。我可以用这样的 for 循环来做到这一点:

all_key2 = ""
english_count =0 
data = json.load(json_file)
for p in data: 
    if english_count > 2: 
        break 
    #make it all one big string 
    if langid.classify(p["key2"])=="english": 
        #increment english_count 
        #join here 

但由于性能问题,我想避免for 循环......有没有办法做到这一点?

[EDIT] 我只是不切片过滤列表的原因是因为生成过滤列表需要很多时间。我想放置一个最大english_count 条件,以便我只生成整个列表的一部分

【问题讨论】:

  • 什么性能问题? “过早的优化是万恶之源”xkcd.com/1691矢量化方法不能提前停止,for循环可以(使用break
  • @cco 我有无数个对象,每个对象都有很多长字符串。使用 for 循环花费的时间太长,.join() 的性能显着提升
  • 列表推导也不能提前停止;将始终运行整个列表。
  • @cco 所以....我必须使用 for 循环吗?或者找到比列表推导更快的方法?
  • 我喜欢列表推导,但不是在提早停止很重要的情况下。在这些情况下,普通的for 循环是一个很好的工具(生成器是另一种提前停止的方法,但我认为对于这种情况来说太复杂了)。

标签: python json string python-3.x


【解决方案1】:

使用for 循环而不是列表推导可以让您提前停止,如下所示:

filtered_list = []
for elem in data:
    if langid.classify(elem["key2"])=="english":
        filtered_list.append(elem["key2"])
        if len(filtered_list) > 2:   # or whatever your max is
            break
result = " ".join(filtered_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2015-08-05
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多