Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从不规则嵌套列表中获取值_Python_Python 2.7_List_Dictionary_Nested - Fatal编程技术网

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

Python 从不规则嵌套列表中获取值,python,python-2.7,list,dictionary,nested,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] -->TypeErro

我有一个嵌套列表(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'
您可以尝试以下方法:

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]

实现这一点的简单方法是在列表中使用双循环:

record = [
    [{'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}],
]

output = [d['0.5'] for row in record for d in row if '0.5' in d]
print(output)
输出

[5, 5]

不要使用
列表
作为变量名。为什么要编辑问题正文并在此处更改变量名,请在代码中执行此操作!您只想打印这些值吗?或者你想把它们放在一个列表中?如果你想要一个列表,你只想要一个简单的列表吗?或者你想要一个与原始列表相对应的列表吗?好的,很好,这很有效。如果我理解正确,那么s是完整的列表,c列表和b包含dict的每个键和值。