2013-10-02 80 views
-2

我需要Python來搜索給定列表的所有子列表,但是當我搜索其中僅包含其中一個元素的元素時,這不起作用。例如,這是我的代碼:在Python中搜索多個相同列表的子列表

data = [[4,5],[4,7]] 
search = 4 
for sublist in data: 
    if search in sublist: 
     print("there", sublist) 

    else: 
     print("not there") 
     print(data) 

並且如果我的搜索包含在列表的所有子列表中,則此功能非常有效。但是,如果我的搜索,例如,5,然後我得到:

there [4,5] #I only want this part. 
not there # I don't want the rest. 
[[4, 5], [4, 7]] 

編輯: 基本上,我需要Python來列出所有搜索包含在列表中,但如果搜索只包含在一個子列表,我只想要print("there", sublist)。換句話說,我只想讓Python識別搜索所在的位置,而不是輸出它不在的位置,所以沒有print("not there") print(data)

+1

你需要弄清楚你的期望輸出是什麼。如果它在三個子列表中的兩個中呢?你希望你的搜索停在第一個,還是......? – roippi

+0

我同意roippi,你的問題很混亂。在print(「there」,sublist)之後,這看起來像是一個簡單的中斷,但是我不確定,因爲我不知道你真正想要什麼。 – btse

+0

對我來說很清楚,哪個答案應該是@tcaswell已經回答的。 – justhalf

回答

2

嘗試使用布爾標記。例如:

data = [[4,5],[4,7]] 
search = 5 
found = false 
for sublist in data: 
    if search in sublist: 
     print("there", sublist) 
     found = true 
if found == false: 
    print("not there") 
    print(data) 

這樣的打印數據是外部for循環,不會被每個子列表中發現時間不包含搜索打印。

1
data = [[4,5],[4,7]] 
search = 4 
found_flag = False 
for sublist in data: 
    if search in sublist: 
     print("there", sublist) 
     found_flag = True 

#  else: 
#  print("not there") 
#  print(data) 
if not found_flag: 
    print('not found') 

沒有理由包括else條款,如果你不想做不包含搜索值的子名單什麼。

一個漂亮的使用elsefor塊後(但這隻會找到一個條目)(doc):

data = [[4,5],[4,7]] 
search = 4 
for sublist in data: 
    if search in sublist: 
     print("there", sublist) 
     break 
else: 
    print 'not there' 

如果它使通過與出整個循環將執行else塊擊中break

+0

這應該是OP想要的。 – justhalf

+0

我很喜歡這個答案;然而,它是否可以擴展,以便如果搜索包含在多個子列表中,它們都是按時間順序打印而不是僅打印第一個子列表? – 5813

+0

請參閱@ user2255137的關於如何向此循環添加標誌的答案。 – tacaswell

0

你可能會尋找

for sublist in data: 
    if search in sublist: 
     print("there", sublist) 
     break 
    else: 
     print("not there") 

print(data) 
1

什麼你可能嘗試寫:

data = [[4,5],[4,7]] 
search = 4 
found = False 
for sublist in data: 
    if search in sublist: 
     found = True 
     break 
# do something based on found 

一個更好的方式來寫:

any(search in sublist for sublist in data) 
0

數據= [4,5],[4 ,7],[5,6],[4,5]]

search = 5

在數據子列表:

if search in sublist: 

    print "there in ",sublist 

else: 
    print "not there in " , sublist 

有在[4,5]

在不存在[4,7]

有在[5,6 ]

there in [4,5]

我剛剛試過你的代碼,並且在搜索時沒有看到任何錯誤5