python - 有效地将来自 json 对象的字符串附加到一个条件上?

标签 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" 

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

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

最佳答案

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

关于python - 有效地将来自 json 对象的字符串附加到一个条件上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43574639/

相关文章:

python - 如何修改streamlit中的选择框列长度?

python - 当另一个数据库插入一条记录时如何更新一个数据库?

java - 为什么 Jackson 序列化时省略了小数点为零的 Double?

python - 关键词多词时高效搜索关键词

java - 字符串函数 - ReplaceAll 不适用于 "."

C 字符串数组 strtok()

python - 为什么在 python 控制台中的 SQLAlchemy base.metadata.create_all(engine) 中不显示表?

python - 实现了自己的 __getattr__;遇到意外错误

JavaScript 未绑定(bind)

c# - 在 JSON 响应中指定类类型