我想在每个循环中选择不同的数组元素。例如,在下面的代码中,数组和循环计数不等于数组的长度。但我必须在主循环中选择一些元素,然后我会将我的选择附加到新数组。
e1=[1,2,3,4,5,6,7,8,9,10]
c=0
e2=[]
while c<=3:
c+=1
for i in e1:
e2.append(i)
print(e2)
.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
但我想在第一个循环中选择1,在第二个循环中选择2,在第三个循环中选择3。所以新数组必须是[1,2,3]。但是数组的每个元素都是自动生成的。
e1=[1,2,3,4,5,6,7,8,9,10]
e2=[]
c=0
while c<3:
e2.append(e1[c])
c+=1
print(e2)
产量
[1,2,3]
在python中,[]被称为列表。
当你编写for i in e1
时,它迭代列表e1
中的每个元素,然后e2.append(i)
将这个i
中的每一个都附加到新列表e2
中。有效地,语句while c<=3:
确保你这样做(将e1的每个项目附加到e2三次),这不是你想要的。 @prashant的评论将是你想要的一种方式。除非我误解你想要的东西,否则会有一种更加诡异的方式:
e1=[1,2,3,4,5,6,7,8,9,10]
c=0
e2=[]
for i in e1[:3]:
e2.append(i)
print(e2)
列表中的每个项目都可以作为list[item_index]
访问,即e1[0] is 1
,e1[3] is 4
等。列表可以像Qazxswpoi一样“切片”,即list[start_index:end_index+1]
即e1[0:3] gives [1,2,3]