通过从两个其他列表中提取连续元素,将元素添加到Python 3.3中的列表中

时间:2013-12-30 21:58:29

标签: python python-3.x

这只是我学习Python 3.3的第二天,所以我承认我还有很多需要学习的东西。

简而言之,我有两个列表:List1充满奇数,List2充满偶数。它们的长度相同(每个都有五个数字)。

我想创建包含[1,2,3,4,5,6,...]的List4,方法是将List1的每个元素与List2中的相同元素组合,然后递增计数器。我猜想要使用Append。我的问题在于最后的评论。

我还有更多的功能可供学习,但如果有人可以提供帮助,我将非常感激。 毫无疑问,我的程序会更加流畅,但这可以在以后发生。

谢谢!

# Fill list with odd numbers up to 10
a = -1
list1 = []
while a < 10:
    a += 2
    print (a)
    list1.append(a)
print ("a = ", a, "\nList 1 = ", list1)

# Fill list with even numbers up to 10
a = 0
list2 = []
while a < 10:
    a += 2
    print (a)
    list2.append(a)
print ("a = ", a, "\nList2 = ", list2)

#Combine the lists side by side
list3 = []
list3 = list1 + list2
print ('List 3 = ', list3)

#Now combine them in numerical order
list4 = []
for i in range (len(list1)):
    list4.append(list1[i] + list2[i]) #Here is the problem
    print (list4) #Here the List4 is gradually filled up
    i += 1
print ("List4 = ", list4)

2 个答案:

答案 0 :(得分:5)

以下是一些选项:

  • 单独附加每个项目:

    for i in range(len(list1)):
        list4.append(list1[i])
        list4.append(list2[i])
    
  • list4.extend()与列表或元组一起使用:

    for i in range(len(list1)):
        list4.extend([list1[i], list2[i]])
    

以前的方法与您当前的方法最相似,但我可能会使用以下方法之一使用zip()

  • 使用列表理解:

    list4 = [x for t in zip(list1, list2) for x in t]
    
  • 使用循环:

    list4 = []
    for t in zip(list1, list2):
        list4.extend(t)
    

作为旁注,您当前的代码有一些奇怪之处。首先要创建一个包含10个奇数或偶数的列表,你可以使用range()而不是循环,例如:

list1 = list(range(1, 11, 2))
list2 = list(range(2, 11, 2))

您也不需要在for循环中手动递增i

答案 1 :(得分:0)

使用列表推导:

evens = [i for i in range(1,11) if i % 2 == 0]
odds = [i for i in range(1,11) if i % 2 != 0]
both = []
both.extend(evens)
both.extend(odds)
both.sort()

print(both)