简体   繁体   中英

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.

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])]

[(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])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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