[英]How to change the for loop to list comprehension?
In the following code snippet:在以下代码片段中:
from collections import OrderedDict
data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]
sale_list = []
for i in range(2):
sale_list.append(list(data[i].items())[0][1])
print(sale_list)
The output is:输出是:
['143017', '243215']
I wonder how to change the for loop to a list comprehension?我想知道如何将 for 循环更改为列表理解?
from collections import OrderedDict
data = [OrderedDict([('sale', '143017'), ('profit', '345'), ('quantity', '45')]),
OrderedDict([('sale', '243215'), ('profit', '400'), ('quantity', '105')]),
OrderedDict([('sale', '98342'), ('profit', '100'), ('quantity', '55')])]
sale_list = [ list(data[i].items())[0][1] for i in range(2) ]
print(sale_list)
This should work, here is a basic example这应该有效,这是一个基本示例
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
Would instead be反而是
h_letters = [ letter for letter in 'human' ]
print( h_letters)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.