Python 将json对象中的字符串有效地附加到一个条件中?
所以我有一个json对象数组,看起来像:Python 将json对象中的字符串有效地附加到一个条件中?,python,json,string,python-3.x,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 = [{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"
但这需要花费很多时间,因为我有无数的对象和长字符串。有没有更快的方法来完成这个浓缩
[EDIT]正在研究函数,这可能是一种方法吗 upvote用于使用列表-而不是带有join的gencomp。是否应将其反转(数据)?行动是prepending@Luchko非常感谢。康卡特的顺序对我来说并不重要,我会调查加入:)是的,没问题。您还可以在列表中添加
if
语句。(请参阅更新)此外,您甚至可以在添加到列表之前通过使用func(elem[“key”])
而不是列表中的elem[“key”]
对每个元素进行预处理comprehension@ocean800我刚刚更新了用空格符号(“.join”代替“.join”连接元素的代码
all_key2 = " ".join([elem["key2"] for elem in data if langid.classify(elem["key2"])=="english"])