Python 从列表中打印特定项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20609376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:50:00  来源:igfitidea点击:

Printing specific items out of a list

pythonlistprinting

提问by user3106855

I'm wondering how to print specific items from a list e.g.given:

我想知道如何从列表中打印特定项目,例如

li = [1,2,3,4]

I want to print just the 3rdand 4thwithin a loop and I have been trying to use some kind of for-loop like the following:

我只想打印循环中的34,并且我一直在尝试使用某种 for 循环,如下所示:

for i in range (li(3,4)):
    print (li[i])

However I'm Getting all kinds of error such as:

但是我收到了各种错误,例如:

TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable

I've been trying to change ()for []and been shuffling the words around to see if it would work but it hasn't so far.

我一直在尝试改变()[]并一直在改变这些词,看看它是否会起作用,但到目前为止还没有。

回答by Chris Seymour

Using slice notation you can get the sublist of items you want:

使用切片符号,您可以获得所需项目的子列表:

>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]

Then just iterate over the sublist:

然后只需遍历子列表:

>>> for item in li[2:]:
...     print item
... 
3
4

回答by Ray

You should do:

你应该做:

for i in [2, 3]:
    print(li[i])

By range(n), you are getting [0, 1, 2, ..., n-1]

通过range(n),你得到[0, 1, 2, ..., n-1]

By range(m, n), you are getting [m, m+1, ..., n-1]

通过range(m, n),你得到[m, m+1, ..., n-1]

That is why you use range, getting a listof indices.

这就是您使用range, 获取list索引的原因。

It is more recommended to use slicinglike other fellows showed.

更推荐slicing像其他人展示的那样使用。

回答by poke

li(3,4)will try to call whatever liis with the arguments 3and 4. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:

li(3,4)将尝试li使用参数3和调用任何内容4。由于列表不可调用,这将失败。如果你想迭代某个索引列表,你可以像这样指定它:

for i in [2, 3]:
    print(li[i])

Note that indexes start at zero, so if you want to get the 3and 4you will need to access list indexes 2and 3.

请注意,索引从零开始,因此如果要获取34,则需要访问列表索引23

You can also slice the list and iterate over the lists instead. By doing li[2:4]you get a list containing the third and fourth element (i.e. indexes iwith 2 <= i < 4). And then you can use the for loop to iterate over those elements:

您还可以将列表切片并迭代列表。通过这样做,li[2:4]您将获得一个包含第三个和第四个元素(即i带有 的索引2 <= i < 4)的列表。然后你可以使用 for 循环来迭代这些元素:

for x in li[2:4]:
    print(x)

Note that iterating over a list will give you the elements directly but not the indexes.

请注意,遍历列表将直接为您提供元素而不是索引。