列表推导式与早期条件检查

huangapple go评论89阅读模式
英文:

List comprehension with early conditional check

问题

以下是给定的代码片段的中文翻译:

对于给定的列表 l

l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]

我想要得到所有值的单一列表

r = [1, 2, 2, 8, 6, 32]

和这段代码

r = []
for item in l:
    if 'k' in item:
        for i in item['k']:
            r += [i]

是否有一种优雅的列表推导解决方案来处理这种类型的列表?

显然,

[i for i in item['k'] if 'k' in item for item in l]

会失败,因为在检查条件之前访问了 item['k']。有什么想法吗?

英文:

For the given list l

l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]

where I would like to have a single list of all values

r = [1, 2, 2, 8, 6, 32]

and the code

r = []
for item in l:
    if 'k' in item:
        for i in item['k']:
            r += [i]

is there an elegant list comprehension solution for this kind of list?

Obviously,

[i for i in item['k'] if 'k' in item for item in l]

fails, because item['k'] is accessed before the condition is checked. Any ideas?

答案1

得分: 4

使用 get 方法在 k 不存在时提供一个空列表进行迭代。

r = [i for d in l for i in d.get('k', [])]

或者,在尝试访问其值之前检查是否存在 k

r = [i for d in l if 'k' in d for i in d['k']]
英文:

Use get to provide an empty list to iterate over if k doesn't exist.

r = [i for d in l for i in d.get('k', [])]

Or, check for k before you try to access its value.

r = [i for d in l if 'k' in d for i in d['k']]

答案2

得分: 1

您的列表理解几乎是正确的,只是列表理解内部语句的顺序错误。请尝试以下方法:

l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]
answer = [i for item in l for i in item['k'] if 'k' in item]
print(answer)

这符合您的要求吗?

英文:

You almost have the right solution with your list comprehension. It is just that the order of statements inside list comprehension is wrong. Please try the following.

l = [{'k': [1, 2]}, {'k': [2, 8]}, {'k': [6, 32]}, {}, {'s': 0}]
answer = [i for item in l if 'k' in item for i in item['k'] ]
print(answer)

Is this what you wanted?

huangapple
  • 本文由 发表于 2020年1月7日 01:58:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定