[英]Printing python specific list indexes using for loop
我有一个列表l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,]
现在,我想使用循环单独打印索引4,6,9,10
我试过了:
for i in l1:
Print(i[4]..)
但它说: int is not subscriptable
我假设这是用于家庭作业,因此您想为此使用循环。 当您i in l1
说i in l1
每个元素i
都是一个int
,因此无法对其建立索引。
如果要专门打印索引4、6、9、10中的元素,则需要将它们放在列表中并对其进行迭代。 因此,例如:
l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,]
to_print = [4, 6, 9, 10] # So if you want to print other/more index positions then modify this. Note that you may want to do a length check too before using these indexes as is.
for i in to_print:
print(l1[i])
如果您只想按索引遍历列表中的所有项目,则可以执行以下操作:
l1 =[1,56,67,79,90,47,8,56,79,84,76,79,68]
for i in range(len(l1)):
if i in (4, 6, 9, 10):
print(l1[i])
话虽如此,这不是最有效的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.