[英]Python list and for-loop
a = ["a","b","c","d","e","f"]
for i in range(len(a)):
print(i)
The output of this code is: 0 1 2 3 4 5
这段代码的output是:
0 1 2 3 4 5
How can I modify my code so that the output will be: 1 2 3 4 5
or only 2 3 4
without changing the values of the a variable
?如何修改我的代码,使 output 为:
1 2 3 4 5
或仅2 3 4
而不更改a variable
的值? I just want to extract some parts of the iteration and not the whole.我只想提取迭代的某些部分而不是全部。
I just want to extract 1 2 3 4 5
or 2 3 4
in my code without altering the aforementioned array.我只想在我的代码中提取
1 2 3 4 5
或2 3 4
而不改变上述数组。 So what I did was this:所以我所做的是:
a = ["a","b","c","d","e","f"]
for i in range(len(a)):
if i == 0:
continue
print(i)
Output: 1 2 3 4 5
without the 0
Output:
1 2 3 4 5
没有0
And if I only want to extract 2 3 4
what I did was this:如果我只想提取
2 3 4
我所做的是:
a = ["a","b","c","d","e","f"]
for i in range(len(a)):
if i < 2:
continue
elif i == 5:
continue
print(i)
Output: 2 3 4
Output:
2 3 4
You can try using slicing:您可以尝试使用切片:
left to right indexing works as 0 to len(a)-1
从左到右的索引从 0 到
len(a)-1
and right to left is -1 to -len(a)从右到左是 -1 到 -len(a)
Syntax is:语法是:
a[start_index:end_index]
Above can give you elements as output then you can apply index function of list to get the index values.上面可以为您提供元素 output 然后您可以应用列表的索引 function 来获取索引值。
NOTE: This approach will work if you want to extract an intact part of a list.注意:如果您想提取列表的完整部分,此方法将起作用。 It won't iterate on whole list, instead only on the part you want to extract.
它不会遍历整个列表,而只会遍历您要提取的部分。
While giving slicing remember end_index
is not included.在给出切片时记住
end_index
不包括在内。
For extracting 1,2,3,4,5:用于提取 1,2,3,4,5:
for i in a[1:]:
print(a.index(i))
#or
For extracting 2,3,4:用于提取 2、3、4:
for i in a[2:5]:
print(a.index(i))
As you mentioned you are new to this, then let's understand what's happening first then we can modify it according to our requirements.正如你提到的你是新手,那么让我们先了解发生了什么,然后我们可以根据我们的要求对其进行修改。 for i in range(len(a)): The range() function is used to generate a sequence of numbers.
for i in range(len(a)): range() function 用于生成数字序列。 here,from (0 to len(a)-1) and here len(a)=6 so your for loop is iterating from 0 to 5. Now if we wanna modify our output say we want 2,3,4 then we can provide an 'if' statement to select any particular subset ie
这里,从 (0 到 len(a)-1) 和这里 len(a)=6 所以你的 for 循环从 0 迭代到 5。现在如果我们想修改我们的 output 说我们想要 2,3,4 那么我们可以向 select 任何特定子集提供“if”语句,即
for i in range(len(a)):
if(i>1) & (i<5):
print(i)
or, you can try slicing if u are comfortable with: for output as 2,3,4或者,如果您愿意,可以尝试切片:对于 output 为 2,3,4
print(a[2:5])
remember a[starting:ending+1]记住一个[开始:结束+1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.