从不规则的嵌套列表中获取值

时间:2017-11-07 14:56:36

标签: python python-2.7 list dictionary nested

我有一个嵌套列表(dict列表列表),其中第二个列表是不规则的。我想获取数组中某个键的所有值。

每行列表:

[{'0.1':1},{'0.2':2},{'0.3':3}]

[{'0.2':2},{'0.3':3},{'0.4':4},{'0.5':5}]

[{'0.1':1},{'0.2':2}]

[{'0.5':5}]

我想要' 0.5'的所有价值观。密钥存储到数组中。我尝试了多个版本:

[record[i]['0.5'] for i in record]

-->TypeError: list indices must be integers, not list

    for d in record.values():
        print(d['0.5'])

-->AttributeError: 'list' object has no attribute 'values'

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

s = [[{'0.1':1},{'0.2':2},{'0.3':3}], [{'0.2':2},{'0.3':3},{'0.4':4},{'0.5':5}], [{'0.1':1},{'0.2':2}], [{'0.5':5}]]
new_vals = [c[0] for c in [[b["0.5"] for b in i if "0.5" in b] for i in s] if c]

输出:

[5, 5]

答案 1 :(得分:0)

这样做的简单方法是在列表解析中使用双循环:

key_buffer_size = 50M

<强>输出

INDEX(worker_id)