这只是我学习Python 3.3的第二天,所以我承认我有很多需要学习的东西.
简而言之,我有两个列表:List1充满奇数,List2充满偶数.它们的长度相同(每个都有五个数字).
我想通过将List1的每个元素与List2中的相同元素组合,并递增计数器来创建包含[1,2,3,4,5,6,...]的List4.我猜想要使用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)
Run Code Online (Sandbox Code Playgroud)
以下是一些选项:
分别附加每个项目:
for i in range(len(list1)):
list4.append(list1[i])
list4.append(list2[i])
Run Code Online (Sandbox Code Playgroud)使用list4.extend()与列表或元组:
for i in range(len(list1)):
list4.extend([list1[i], list2[i]])
Run Code Online (Sandbox Code Playgroud)以前的方法与您当前的方法最相似,但我可能会使用zip()以下方法之一:
使用列表理解:
list4 = [x for t in zip(list1, list2) for x in t]
Run Code Online (Sandbox Code Playgroud)使用循环:
list4 = []
for t in zip(list1, list2):
list4.extend(t)
Run Code Online (Sandbox Code Playgroud)另外,您当前的代码有一些奇怪之处.首先要创建一个奇数或偶数的列表,包括10,你可以使用range()而不是循环,例如:
list1 = list(range(1, 11, 2))
list2 = list(range(2, 11, 2))
Run Code Online (Sandbox Code Playgroud)
您也不需要i在for循环中手动递增.
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |