2013-08-03 72 views
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) 

在此先感謝!

回答

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 
+0

這確實有幫助!謝謝!只是想知道,有沒有辦法沒有對象,只有索引? – choochoopain

+1

你需要有承擔其長度的對象,雖然。你可以在範圍使用'爲我(LEN(newlist)):'然後'newlist [I]',但是這被認爲unpythonic風格。 – DSM

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