简体   繁体   English

使用for循环打印python特定的列表索引

[英]Printing python specific list indexes using for loop

I have a list l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,] 我有一个列表l1 =[1,56,67,79,90,47,08,56,79,84,76,79,68,]

Now, I want to print indices 4,6,9,10 alone using a loop 现在,我想使用循环单独打印索引4,6,9,10

I tried: 我试过了:

for i in l1:
    Print(i[4]..)

But it says: int is not subscriptable 但它说: int is not subscriptable

I am assuming this is for a homework and so you want to use loops for this. 我假设这是用于家庭作业,因此您想为此使用循环。 When you say i in l1 each element i is an int and so it won't work to index it. 当您i in l1i in l1每个元素i都是一个int ,因此无法对其建立索引。

If you are trying to specifically print elements in indexes 4, 6, 9, 10 then you need to put these in a list and iterate over these. 如果要专门打印索引4、6、9、10中的元素,则需要将它们放在列表中并对其进行迭代。 So for ex: 因此,例如:

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])

if you just want to loop over all items in the list by the indexes you could do something like this: 如果您只想按索引遍历列表中的所有项目,则可以执行以下操作:

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])

that being said, this is not the most efficient thing 话虽如此,这不是最有效的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM