简体   繁体   English

append 如何与 python 中的 for 循环一起使用

[英]how does append works with for loop in python

t=int(input())
#c=[i for i in range(t)]
for i in range(t):

    n=int(input())
    a = list(map(int,input().strip().split()))
    b = list()

    for i in range(n):
        if(a[i]==1):
            b.append(i)


    print(b)

when list a is (1 0 1), list b is( 0,2 ) when list a is 1 0 0 1, list b is 0,3 In fact, I suppose the output of list b is ( 1,1) instead of 0, 2 since its definition is to add the obj into list Please tell me if there's something I miss or get wrong, thanks当列表 a 为 (1 0 1) 时,列表 b 为 (0,2) 当列表 a 为 1 0 0 1 时,列表 b 为 0,3 事实上,我认为列表 b 的 output 是 (1,1)的 0, 2 因为它的定义是将 obj 添加到列表中请告诉我是否有遗漏或出错的东西,谢谢

You append i , which is the index, and not a[i] which is the value from a .您是 append i ,它是索引,而不是a[i] ,它是来自a的值。

so b is essentially a list containing all indexes of elements in a that are equal 1所以b本质上是一个列表,包含a中等于1的元素的所有索引

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

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