Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.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 3.x_Dictionary_List Comprehension - Fatal编程技术网

Python 如何通过听写理解达到以下效果?

Python 如何通过听写理解达到以下效果?,python,python-3.x,dictionary,list-comprehension,Python,Python 3.x,Dictionary,List Comprehension,您好,我想从dict获取所有“整数值”: array_test = [{ "result1" : "date1", "type" : "Integer"},{ "result1" : "date2", "type" : "null"}] 我试过: test = {'result1':array_test['result1'] for element in array_test if array_test['type'] == "Integer"} 但是我得到了这个错误: >>&

您好,我想从dict获取所有“整数值”:

array_test = [{ "result1" : "date1",  "type" : "Integer"},{ "result1" : "date2", "type" : "null"}]
我试过:

test = {'result1':array_test['result1'] for element in array_test if array_test['type'] == "Integer"}
但是我得到了这个错误:

>>> test = {'result1':array_test['result1'] for element in array_test if array_test['type'] == "Integer"}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
TypeError: list indices must be integers or slices, not str
>>> 
>>> 

您需要的是列表理解,而不是字典理解:

array_test = [{ "result1" : "date1",  "type" : "Integer"},{ "result1" : "date2", "type" : "null"}]

test = [x for x in array_test if x['type'] == 'Integer']
# [{'result1': 'date1', 'type': 'Integer'}]

为什么??因为所需的输出是一个列表(字典列表)。

您需要的是列表理解,而不是字典理解:

array_test = [{ "result1" : "date1",  "type" : "Integer"},{ "result1" : "date2", "type" : "null"}]

test = [x for x in array_test if x['type'] == 'Integer']
# [{'result1': 'date1', 'type': 'Integer'}]

为什么??因为所需的输出是一个列表(字典列表)。

非常感谢您的支持非常感谢您的支持