英文:
Can I initialize variable in list comprehension?
问题
for col in ws:
for value in col:
new_value = value * 2
blank_list.append(new_value)
这段代码的列表推导写法应该是这样的:
blank_list = [value * 2 for col in ws for value in col]
然后,你不需要再做其他操作。这个列表推导会遍历ws中的每一列和每个值,并将每个值乘以2后添加到blank_list中。
英文:
for col in ws:
for value in col:
new_value = value * 2
blank_list.append(new_value)
What should be the list comprehension for this?
I think of it like this, but I don't know what to write after that -
blank_list = [new_value for col in ws for value in col]
I don't what to do after this ?
答案1
得分: 1
blank_list = [value*2 for col in ws for value in col]
这将给你期望的结果。
示例:
ws = [[1, 2, 3], [4, 5, 6]]
blank_list = [value*2 for col in ws for value in col]
print(blank_list)
# [2, 4, 6, 8, 10, 12]
英文:
blank_list = [value*2 for col in ws for value in col]
This will give you the result you're expecting.
Example:
ws = [[1, 2, 3], [4, 5, 6]]
blank_list = [value*2 for col in ws for value in col]
print(blank_list)
# [2, 4, 6, 8, 10, 12]
答案2
得分: 1
这种情况的最佳答案是@sud给出的答案。但对于更复杂的列表推导,您可以编写:
blank_list = [result for col in ws for value in col for result in [value * 2]]
Python进行了优化,以便在已知为一个元素的列表上循环时将其处理为赋值。语法有点丑陋,但当您需要在列表推导中使用临时变量时,这是有用的。
英文:
The best answer for this case is the one given by @sud above. But for more complicated list comprehensions, you can write:
blank_list = [result for col in ws for value in col for result in [value * 2]]
Python has an optimization so that looping over a list that is known to be one element is handled as an assignment. The syntax is a little ugly, but it's useful to know when you need a temporary variable in list comprehension.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论