2017-04-23 15 views
3

所以我有一個看起來像JSON對象的數組:從一個條件的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功能,可能是要走的路?

回答

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

upvote for list-,而不是gencomp with join。 – timgeb

+0

是否應該顛倒(數據)?該OP正在加入 –

+0

@Luchko謝謝! Concat順序對我無關緊要,我會考慮加入:) – ocean800

相關問題