如何执行三个循环

时间:2019-05-31 14:24:18

标签: python

这行代码有问题:

res = [[int(i) for i in sub] for i in test_list for sub in i]

此行将执行时,int(i)在第一次迭代中将得到24,然后将这24个值转换为[2,4],如下面列出的输出所示。 24如何转换为列表的[2,4]?为了转换成列表,数字应该是可迭代的,不是吗?

   test_list = [['24'], ['45'], ['78'], ['40']] 
   print("The original list : " + str(test_list)) 
   res = [[int(i) for i in sub] for i in test_list for sub in i] 
   print("The list after conversion : " + str(res)) 

输出为:

     The original list : [['24'], ['45'], ['78'], ['40']]
     The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]

3 个答案:

答案 0 :(得分:0)

给予

res = [[int(i) for i in sub] for i in test_list for sub in i]

列表理解等效于:

test_list = [['24'], ['45'], ['78'], ['40']]   
res = []
for i in test_list: #so, i is similar to ['24'] initially
    for sub in i: #so, sub would be similar to a string '24' initially
        temp = [int(i) for i in sub] #iterate through string 1 character at a time. convert to str.
        res.append(temp)

如果您注意到,我故意将1个列表理解留在里面。可以进一步扩展,但需要注意。 i变量在外部不引用i变量,因为理解带有它们自己的范围,不会泄漏。

整个代码等效于:

res = []
for i in test_list:
    for sub in i:
        temp = []
        for i_ in sub: #using i_ just to elaborate it is a different value 
            temp.append(int(i_))
        res.append(temp)

输出:

[[2, 4], [4, 5], [7, 8], [4, 0]]

答案 1 :(得分:0)

当您进行列表理解时,输出为列表。输入可以是任何可迭代的-在这里,您使用的是字符串-但输出始终是列表。所以当你这样做

[int(i) for i in '24']

您正在查看

[int('2'), int('4')]

解析为

[2, 4]

如果您的目标是从此列表中获取整数值:

test_list = [['24'], ['45'], ['78'], ['40']] 

更好的方法是只有一个for循环/列表理解,而不是三个。无需遍历内部“列表”-如果它们只是一个元素,则可以手动解决:

res = [int(num[0]) for num in test_list]  # num == ['24'], so num[0] == '24'
# res == [24, 45, 78, 40]

答案 2 :(得分:0)

for i in test_list将遍历列表并返回['24'] -> ['45'] -> ['78'] -> ['40']

for sub in i将遍历这些列表。每个元素仅包含一个将返回的元素。

for i in sub将遍历字符串并返回每个字符:''24':'2'->'4'

如此

[int(i) for i in sub]将向您返回以下列表:[[2, 4], [4, 5], [7, 8], [4, 0]]


如果需要整数列表,可以使用:

res = [int(l[0]) for l in test_list]

  

[24, 45, 78, 40]