[英]I want to choose different element in each loop
I want to choose different element of array in each loop.我想在每个循环中选择不同的数组元素。 For example, in the code below array and loop counts are not equal to length of array.例如,在下面的代码中,数组和循环计数不等于数组的长度。 But I must choose some elements in the main loop and then I will append my choices to new array.但是我必须在主循环中选择一些元素,然后我会将我的选择附加到新数组中。
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]
But I want to choose 1 in first loop, 2 in second loop and 3 in third loop.但我想在第一个循环中选择 1,在第二个循环中选择 2,在第三个循环中选择 3。 So new array must be [1, 2, 3].所以新数组必须是 [1, 2, 3]。 But every element of array is generated automatically.但是数组的每个元素都是自动生成的。
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)
output输出
[1,2,3]
In python, [] are called lists.在python中,[]被称为列表。
When you are writing for i in e1
, it iterates over every element in the list e1
, and then e2.append(i)
appends every one of this i
into the new list e2
.当您for i in e1
编写代码时,它会遍历列表e1
中的每个元素,然后e2.append(i)
将这个i
每一个附加到新列表e2
。 Effectively the statement while c<=3:
makes sure you do this (append every item of e1 to e2 for three times) which is not what you want.有效的语句while c<=3:
确保您执行此操作(将 e1 的每个项目附加到 e2 三次),这不是您想要的。 @prashant's comment would be one way to do what you want. @prashant 的评论将是做你想做的一种方式。 A more pythonic way would be, unless I am mistaken about what you want:一个更pythonic的方式是,除非我误会你想要什么:
e1=[1,2,3,4,5,6,7,8,9,10]
c=0
e2=[]
for i in e1[:3]:
e2.append(i)
print(e2)
Every item in a list can be accessed as list[item_index]
ie e1[0] is 1
, e1[3] is 4
, etc. And lists can be 'sliced' as list[start_index:end_index+1]
ie e1[0:3] gives [1,2,3]
ie e1[0], e1[1], e1[2]
列表中的每一项都可以作为list[item_index]
访问,即e1[0] is 1
, e1[3] is 4
等。列表可以被“切片”为list[start_index:end_index+1]
即e1[0:3] gives [1,2,3]
即e1[0], e1[1], e1[2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.