【问题标题】:Appending strings from json object on a condition together efficiently?有效地将条件上的json对象中的字符串附加在一起?
【发布时间】:2017-04-23 18:02:44
【问题描述】:

所以我有一个 json 对象数组,看起来像:

data = [{key1: 123, key2:"this is the first string to concatenate"},
 {key1: 131, key2:"this is the second string to concatenate"},
 {key1: 152, key2:"this is the third string to concatenate"} ] 

基本上,我现在使用的 for 循环如下:

all_key2 = ""
data = json.load(json_file)
for p in data: 
    #make it all one big string 
    if langid.classify(p["key2"])=="english": 
        all_key2 = p["key2"] + " " + all_key2 

所以答案应该是:

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

但这需要很多时间,因为我有大量的对象和长字符串。有没有更快的方法来完成这种连接?

[编辑] 正在研究lambda 函数,这可能是要走的路吗?

【问题讨论】:

    标签: python json string python-3.x


    【解决方案1】:
    all_key2 = " ".join([elem["key2"] for elem in data if langid.classify(elem["key2"])=="english"])
    

    【讨论】:

    • 赞成使用 list- 而不是 gencomp 和 join。
    • 是否应该反转(数据)? OP 正在前置
    • @Luchko 谢谢! Concat 顺序对我来说无关紧要,我会考虑加入 :)
    • 是的,没问题。您还可以在列表理解中添加if 语句。 (查看更新)此外,您甚至可以在添加到列表之前对每个元素进行预处理,方法是在列表推导中使用 func(elem["key"]) 而不是 elem["key"]
    • @ocean800 我刚刚更新了使用空格符号连接元素的代码(“” .join 而不是“”.join
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多