简体   繁体   English

Python:循环遍历多个列表并附加到列表

[英]Python: Looping Through Multiple lists and Appending to list

I have 2 lists and using a range function i need to go through the list and print out a list of 10 tuples.我有 2 个列表,使用范围函数我需要遍历列表并打印出 10 个元组的列表。

list_1=[3,43,34,34,32,43,54,45,45]
list_2=[3,43,34,34,2,34,23,23,43]

for indenti in range(10):
   for list1 in list_1:
       for list2 in list_2:
             temp = (identi,[list1,list2])
             table.append(temp)
print(table)

The above function is supposed to print a list of tuples like the following.上面的函数应该打印一个如下所示的元组列表。 But when I print the table the last tuple is printed [(9, [41.74490743920966, 46.86562115881449, 0])]但是当我打印表格时,最后一个元组被打印出来[(9, [41.74490743920966, 46.86562115881449, 0])]

[(0, [41.74490743920966, 46.86562115881449, 0])]
[(1, [41.74490743920966, 46.86562115881449, 0])]
[(2, [41.74490743920966, 46.86562115881449, 0])]
[(3, [41.74490743920966, 46.86562115881449, 0])]

Can someone point to me what I am missing or doing wrong that my code only prints out the last tuple insted of all the tuples in a list like the example above.有人可以指出我遗漏了什么或做错了什么,我的代码只打印出列表中所有元组的最后一个元组,如上面的示例。

If I understand your desired behavior:如果我理解你想要的行为:

>>> list_1=[3,43,34,34,32,43,54,45,45]
>>> list_2=[3,43,34,34,2,34,23,23,43]
>>> [(i, [list_1[i],list_2[i]]) for i in range(len(list_1))]

Output输出

[(0, [3, 3]), (1, [43, 43]), (2, [34, 34]), (3, [34, 34]), (4, [32, 2]), (5, [43, 34]), (6, [54, 23]), (7, [45, 23]), (8, [45, 43])]

Formatted, that result is格式化,结果是

[(0, [3, 3]),
 (1, [43, 43]),
 (2, [34, 34]),
 (3, [34, 34]),
 (4, [32, 2]),
 (5, [43, 34]),
 (6, [54, 23]),
 (7, [45, 23]),
 (8, [45, 43])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM