0

我有一个由一定长度的子列表组成的列表,有点像[["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]. 我想要做的是找到没有特定长度的子列表的索引,然后将该索引打印出来。例如,在示例列表中,最后一个子列表的长度不是四,所以我会打印list 2 does not have correct length. 这是我到目前为止所拥有的:

for i in newlist:
    if len(i) == 4:
        print("okay")
elif len(i) != 4:
    ind = i[0:]     #this isnt finished; this prints out the lists with the not correct length, but not their indecies 
    print("not okay",ind)

提前致谢!

4

2 回答 2

1

当您需要索引和对象时,您通常可以使用enumerate,它会产生(index, element)元组。例如:

>>> seq = "a", "b", "c"
>>> enumerate(seq)
<enumerate object at 0x102714eb0>
>>> list(enumerate(seq))
[(0, 'a'), (1, 'b'), (2, 'c')]

所以:

newlist = [["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]

for i, sublist in enumerate(newlist):
    if len(sublist) == 4:
        print("sublist #", i, "is okay")
    else:
        print("sublist #", i, "is not okay")

生产

sublist # 0 is okay
sublist # 1 is okay
sublist # 2 is not okay
于 2013-08-03T02:20:07.133 回答
0

我认为 DSM 得到了您想要的答案,但您也可以使用index 方法并编写如下内容:

new_list = [["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]
size_filter = 4
# all values that are not 4 in size
indexes = [new_list.index(val) for val in new_list if len(val)!=size_filter]
# output values that match
for index in indexes:
    print("{0} is not the correct length".format(index))
于 2013-08-03T04:41:33.020 回答