是否可以有效地将json对象中的字符串附加到条件上?

时间:2017-04-23 18:02:44

标签: python json string python-3.x

所以我有一个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" 

但是这需要花费很多时间,因为我有一些bajillion对象和长串。有没有更快的方法来完成这个连接?

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

1 个答案:

答案 0 :(得分:4)

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