如何遍历字典列表,获取条件值并将其添加到新列表?
How to iterate through a list of dictionaries, take the value of a condition and add it to a new list?
所以我得到了一个很大的列表,里面有字典。这是其中一个词典的一个小例子:
[{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'},
{'id': 384,
我想遍历这些字典,获取大于 0 的 calls 和 wounded 的值,并将这些值添加到新列表中。我试过这样做:
lijst = []
for x in nee:
if x['calls'] > '0':
list.append(x)
if x['wounded'] > '0':
list.append(x)
但这行不通。还有一些 calls 和 wounded 的值为 None,所以 > 0 也不起作用
这个有效:
nee = [{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'}]
l = []
for x in nee:
if x['calls'] > 0:
l.append(x['calls'])
if x['wounded'] > 0:
l.append(x['wounded'])
print(l)
您还可以对两个列表理解求和:
wounded = [x['wounded'] for x in nee if x['wounded'] > 0]
calls = [x['calls'] for x in nee if x['calls'] > 0]
new_list = wounded + calls
print(new_list)
您可以使用嵌套列表理解,因为您需要遍历您的数据和条件,例如,如下所示:
data = [
{'id': 32,
'calls': '1',
'wounded': '2',
'dog': True,
'hitrun': 'David Williams'},
{'id': 32,
'calls': None,
'wounded': None,
'dog': True,
'hitrun': 'David Williams'}
]
output = [
x[field] for x in data for field in ['calls', 'wounded'] if x[field] is not None and int(x[field]) > 0
]
print(output)
>>> ['1', '2']
你可以试试这个:
data = [
{'id': 32,
'calls': '1',
'wounded': '2',
'dog': True,
'hitrun': 'David Williams'},
{'id': 32,
'calls': None,
'wounded': None,
'dog': True,
'hitrun': 'David Williams'}
]
call_wounded_list = [dict_[f] for dict_ in data for f in ['calls', 'wounded'] if str(dict_[f]).isdigit() and float(dict_[f]) > 0]
这个returns
>>> call_wounded_list
['1', '2']
所以我得到了一个很大的列表,里面有字典。这是其中一个词典的一个小例子:
[{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'},
{'id': 384,
我想遍历这些字典,获取大于 0 的 calls 和 wounded 的值,并将这些值添加到新列表中。我试过这样做:
lijst = []
for x in nee:
if x['calls'] > '0':
list.append(x)
if x['wounded'] > '0':
list.append(x)
但这行不通。还有一些 calls 和 wounded 的值为 None,所以 > 0 也不起作用
这个有效:
nee = [{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'}]
l = []
for x in nee:
if x['calls'] > 0:
l.append(x['calls'])
if x['wounded'] > 0:
l.append(x['wounded'])
print(l)
您还可以对两个列表理解求和:
wounded = [x['wounded'] for x in nee if x['wounded'] > 0]
calls = [x['calls'] for x in nee if x['calls'] > 0]
new_list = wounded + calls
print(new_list)
您可以使用嵌套列表理解,因为您需要遍历您的数据和条件,例如,如下所示:
data = [
{'id': 32,
'calls': '1',
'wounded': '2',
'dog': True,
'hitrun': 'David Williams'},
{'id': 32,
'calls': None,
'wounded': None,
'dog': True,
'hitrun': 'David Williams'}
]
output = [
x[field] for x in data for field in ['calls', 'wounded'] if x[field] is not None and int(x[field]) > 0
]
print(output)
>>> ['1', '2']
你可以试试这个:
data = [
{'id': 32,
'calls': '1',
'wounded': '2',
'dog': True,
'hitrun': 'David Williams'},
{'id': 32,
'calls': None,
'wounded': None,
'dog': True,
'hitrun': 'David Williams'}
]
call_wounded_list = [dict_[f] for dict_ in data for f in ['calls', 'wounded'] if str(dict_[f]).isdigit() and float(dict_[f]) > 0]
这个returns
>>> call_wounded_list
['1', '2']