繁体   English   中英

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

[英]while-loop problem for acess a list element

  • 我想 append [1,2][[1], [2], [3]]的每个元素,因此,我想要的最终数组是[[1,1], [1,2], [2,1], [2,2], [3,1], [3,2]]

    但是我的代码有个错误我还认不出来,下面的python代码的结果是[[1, 1, 2], [1, 1, 2], [2, 1, 2], [2, 1, 2], [3, 1, 2], [3, 1, 2]]

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

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

在此示例中,使用for loop会更有用。 您可以使用它来循环遍历这两个列表,以及成对的 append。

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

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

print(tor)

您可以使用 Python 列表comprehension来实现这一点:

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

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

print(result)
  • 对于这种操作,不要使用While循环,而是使用for循环。 与可迭代对象一起使用更加简洁和简单。

暂无
暂无

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

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