如何迭代字典列表,获取条件值并将其添加到新列表中?

2024-10-03 17:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个很大的清单,里面有字典。以下是其中一本词典的一个小示例:

[{'id': 32,
'calls': 1,
'wounded': 2,
'dog': True,
'hitrun': 'David Williams'},
{'id': 384,

我想遍历这些字典,获取调用的值,如果它们大于0,则获取它们的值,并将这些值添加到新列表中。我试着这样做:

lijst = []
for x in nee:
if x['calls'] > '0':
    list.append(x)
if x['wounded'] > '0':
    list.append(x)

但这不起作用。也有一些呼叫和受伤,但它们的价值为零,因此>;0也不工作


Tags: idtrue示例列表if字典list词典
3条回答

您可以使用嵌套列表理解,因为您需要迭代数据和条件,例如,类似以下内容:

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]

这是回报

>>> call_wounded_list
['1', '2']

这项工作:

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)

相关问题 更多 >