简体   繁体   English

访问列表元素的while循环问题

[英]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]]我想 append [1,2][[1], [2], [3]]的每个元素,因此,我想要的最终数组是[[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]]但是我的代码有个错误我还认不出来,下面的python代码的结果是[[1, 1, 2], [1, 1, 2], [2, 1, 2], [2, 1, 2], [3, 1, 2], [3, 1, 2]]

The python code: python 代码:

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它将是eleman=arz[each].copy()因为列表是可变的,因此每次更改原始列表中的元素时,它都会反映在结果数组中

In this example it would be more useful to use a for loop .在此示例中,使用for loop会更有用。 You can use it to loop through both lists, and append in pairs.您可以使用它来循环遍历这两个列表,以及成对的 append。

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:您可以使用 Python 列表comprehension来实现这一点:

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.对于这种操作,不要使用While循环,而是使用for循环。 It is much cleaner and simpler to use with iterables.与可迭代对象一起使用更加简洁和简单。

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

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