List 打印子列表的索引时出错?
我有一个由一定长度的子列表组成的列表,有点像List 打印子列表的索引时出错?,list,python-3.x,indexing,List,Python 3.x,Indexing,我有一个由一定长度的子列表组成的列表,有点像[[“a”、“b”、“c”、“d”]、[“a”、“b”、“c”、“d”]、[“a”、“b”、“c”、“d”、“e”]。我要做的是找到子列表中没有特定长度的索引,然后打印出该索引。例如,在示例列表中,最后一个子列表的长度不为4,因此我将打印列表2的长度不正确。这就是我到目前为止所做的: for i in newlist: if len(i) == 4: print("okay") elif len(i) != 4: ind
[[“a”、“b”、“c”、“d”]、[“a”、“b”、“c”、“d”]、[“a”、“b”、“c”、“d”、“e”]
。我要做的是找到子列表中没有特定长度的索引,然后打印出该索引。例如,在示例列表中,最后一个子列表的长度不为4,因此我将打印列表2的长度不正确。这就是我到目前为止所做的:
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)
提前谢谢 当同时需要索引和对象时,通常可以使用枚举
,这将生成(索引,元素)
元组。例如:
>>> seq = "a", "b", "c"
>>> enumerate(seq)
<enumerate object at 0x102714eb0>
>>> list(enumerate(seq))
[(0, 'a'), (1, 'b'), (2, 'c')]
产生
sublist # 0 is okay
sublist # 1 is okay
sublist # 2 is not okay
我认为DSM得到了您想要的答案,但您也可以使用,并编写如下内容:
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))
这真的很有帮助!谢谢我只是想知道,有没有一种方法不需要对象,只需要索引?不过,你需要让对象测量它的长度。您可以对范围内的i使用(len(newlist)):
,然后使用newlist[i]
,但这被认为是非音速风格。
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))