简体   繁体   中英

while-loop problem for acess a list element

  • I want to append each element of [1,2] to [[1], [2], [3]] and as a consequence, the final array that I want is [[1,1], [1,2], [2,1], [2,2], [3,1], [3,2]]

    But my code has a mistake I couldn't recognize it yet, and the result of the python code below is [[1, 1, 2], [1, 1, 2], [2, 1, 2], [2, 1, 2], [3, 1, 2], [3, 1, 2]]

The python code:

tor=[]
arr=[1,2]
arz=[[1], [2], [3]]

each=0
while each<len(arz):
       
    eleman=arz[each]
    index=0
    while index < len(arr):
        k=arr[index]
        eleman=arz[each]
        eleman.append(k)
        tor.append(eleman)
        index = index+1
    
    each=each+1

it would be eleman=arz[each].copy() as lists are mutable so every time you change an element in the original list it will get reflected in the resultant array

In this example it would be more useful to use a for loop . You can use it to loop through both lists, and append in pairs.

arr = [1, 2]
arz = [[1], [2], [3]]
tor = []

for i in arz:
    for j in (arr):
        tor.append([i[0], j])

print(tor)

You can use Python list comprehension to achieve this in one line:

a1 = [1, 2]
a2 = [[1], [2], [3]]

result =  [[i[0], j] for i in a2 for j in a1]

print(result)
  • For this kind of operations don't use While loop but the for loop. It is much cleaner and simpler to use with iterables.

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