从列表中打印特定项目 [英] Printing specific items out of a list
本文介绍了从列表中打印特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何从给出的列表 中打印特定项目:
I'm wondering how to print specific items from a list e.g. given:
li = [1,2,3,4]
我只想在一个循环中打印第3 rd 和第4 th ,并且我一直在尝试使用如下所示的for循环:>
I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:
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.
推荐答案
使用切片符号可以获取所需项目的子列表:
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
然后遍历子列表:
>>> for item in li[2:]:
... print item
...
3
4
这篇关于从列表中打印特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文