英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论