我有一个列表,该列表由一定长度的子列表组成,有点像[["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)
提前致谢!
答案 0 :(得分: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
答案 1 :(得分:0)
我认为DSM得到了你所追求的答案,但你也可以使用index method并写下如下内容:
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))