访问列表元素的whileloop问题

2024-06-28 16:16:14 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 我想将[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

Tags: 代码元素indexlen错误数组toreach
3条回答

在本例中,使用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)

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

您可以使用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循环。它更干净,使用起来更简单

相关问题 更多 >