如何将for循环更改为列表理解?

时间:2020-10-31 03:48:07

标签: python python-3.x

在以下代码段中:

<component :is="currentTab"></component>
// Idk how to pass them within this component tag

输出为:

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)

我想知道如何将for循环更改为列表理解吗?

1 个答案:

答案 0 :(得分:1)

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)

这应该有效,这是一个基本示例

h_letters = []

for letter in 'human':
    h_letters.append(letter)

print(h_letters)

相反会

h_letters = [ letter for letter in 'human' ]
print( h_letters)