Python)我想添加两个长度顺序不同的列表

2024-05-16 22:16:06 发布

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

我想加上list1=[1,2,3,4,5]list2=[1,1,1,1,1,1,1]

我想要的是

list3=[2,3,4,5,6,1,1]

这是我的错误代码

lis1=[1,2,3,4,5] #len=5
list2=[1,1,1,1,1,1,1] #len=7
if len(list1)>len(list2):
    for i in range(len(list1)):
        list2.append(0) if list2[i]=[]
        list3[i]=list1[i]+list2[i]
else:
    for i in range(len(list2)):
        list1.append(o) if list1[i]=[]
        list3[i]=list1[i]+list2[i]
print(list3)

Tags: inforlenifrangeelseprintappend
3条回答

我会尽量使这段代码尽可能基本。首先,你从不想复制粘贴你的代码。应该首先评估if/else语句。你知道吗

lis1=[1,2,3,4,5] #len=5
list2=[1,1,1,1,1,1,1] #len=7
longer, shorter = [], []
if len(list1) > len(list2):
    longer, shorter = list1, list2
else:
    longer, shorter = list2, list1

现在我们通过简单地将列表命名为longershorter,确定了哪个列表长,哪个列表短。我们的下一个任务是编程。我们要做的是迭代longer列表并添加找到的每个int:

for i in range(len(longer)):
    longer[i] += shorter[i]
print(longer)

我们试着运行这个程序,,它失败了out of range exception。因此,我们确定问题并修复代码:

for i in range(len(longer)):
    if (i > len(shorter)): ## We make sure to not call shorter[i] if there is no such element
        longer[i] += shorter[i]
print(longer)

有什么问题吗?你知道吗

基本上你想把这两个列表加在一起,如果列表不够长,用0填充。所以我直接从你的代码中修改,没有任何库:

list1=[1,2,3,4,5] #len=5
list2=[1,1,1,1,1,1,1] #len=7
list3 = [] # make a list3 
if len(list1)>len(list2):
    for i in range(len(list1)):
       # if list2[i]=[] this line is wrong, you can't compare non-exist element to a empty array
        if i >= len(list2):
            list2.append(0)
        list3.append(list1[i]+list2[i])
else:
    for i in range(len(list2)):
        if i >= len(list1):
            list1.append(0)
        list3.append(list1[i]+list2[i])
print(list3)

您可以使用itertools中的izip_longest

例如:

from itertools import izip_longest
list1=[1,2,3,4,5]
list2=[1,1,1,1,1,1,1]
print([sum(i) for i in izip_longest(list1, list2, fillvalue=0)])

输出:

[2, 3, 4, 5, 6, 1, 1]

相关问题 更多 >