【问题标题】:while-loop problem for acess a list element访问列表元素的while循环问题
【发布时间】:2021-05-10 17:17:58
【问题描述】:
  • 我想将[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

【问题讨论】:

    标签: python arrays list recursion while-loop


    【解决方案1】:

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

    【讨论】:

    • .copy() 的作用是什么?为什么有必要?
    • copy 基本上创建了变量的浅拷贝
    • 我注意到 .copy() 是列表中列表元素的副本(列表列表)所必需的。是这样吗?
    • 是的,需要复制,因为您将项目附加到循环中的同一列表中,这将基本上在循环中使用相同的引用,从而导致您得到的结果
    • 我现在完全明白了!
    【解决方案2】:

    在这个例子中,使用for loop 会更有用。您可以使用它来遍历两个列表,并成对追加。

    arr = [1, 2]
    arz = [[1], [2], [3]]
    tor = []
    
    for i in arz:
        for j in (arr):
            tor.append([i[0], j])
    
    print(tor)
    

    【讨论】:

    • 为什么需要“i[0]”?为什么不是“我”?谢谢你的回答
    • 如果您查看arz:请注意第一项不是1,而是[1]。所以你必须抓住它的第一项。
    • 没关系。它只是一个“列表中的列表”。
    【解决方案3】:

    您可以使用 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 循环。与可迭代对象一起使用更加简洁。

    【讨论】:

    • 感谢您的回答。我故意问这个问题是为了了解问题出在哪里。你能解释一下吗?
    猜你喜欢
    • 2011-06-19
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2017-08-11
    相关资源
    最近更新 更多