【问题标题】:How to iterate through a list of dictionaries, take the value of a condition and add it to a new list?如何遍历字典列表,获取条件值并将其添加到新列表中?
【发布时间】:2020-02-05 22:22:58
【问题描述】:

所以我得到了一个包含字典的大清单。下面是其中一个字典的一个小例子:

[{'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)

但这不起作用。也有一些 call 和受伤的值为 None ,所以 > 0 也不起作用

【问题讨论】:

  • 为什么不起作用?发生什么了? list.append(c) 中的 c 是什么?两个值都必须是 g.t.零。如果值符合条件,完整的字典是否会附加到 new 列表中?
  • 我收到此错误:“str”和“int”实例之间不支持“>”。我认为c是错误的。它应该是 x 。这两个值都必须大于零,但还有另一个问题:其中一些值是 None 所以它给出了另一个错误
  • 您的示例字典值为ints,您的条件语句值为字符串。试试if float(x['calls'] > 0:...if float(x['wounded'] > 0:...

标签: python python-3.x list dictionary nested-lists


【解决方案1】:

您可以使用嵌套列表推导,因为您需要迭代数据和条件,例如,如下所示:

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']

【讨论】:

  • 我收到此错误,似乎无法修复:'>' 在 'str' 和 'int' 的实例之间不受支持
  • @taaaaavi 那是因为您无法将 string 元素与使用 integer> 元素进行比较,我更新了答案来解决这个问题。
  • 谢谢!不过,这个数据集确实有问题,其中也有一些无,所以现在我明白了:int() 参数必须是一个字符串、一个类似字节的对象或一个数字,而不是“NoneType”。我不知道如何删除这些无?
【解决方案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)

【讨论】:

  • 我相信有人会使用itertools 或嵌套列表理解来提供另一种解决方案。
  • 我也尝试过类似的方法,但随后出现此错误:在“str”和“int”的实例之间不支持“>”。然后我尝试将 int 0 设置为 '0' 但这也不起作用
  • 0 不应该是字符串
【解决方案3】:

你可以试试这个:

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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2019-07-15
    • 2021-06-30
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多