2017-06-13 26 views
0

我有這個多的if/else在列表理解蟒蛇

s = ['son','abc','pro','bro'] 
b = ['son','bro'] 
c = ['pro','quo'] 

預期輸出是這樣的。如果輸出中的項目是index(item_in_s),如果它出現在列表b中。或者index(item_in_s)+10如果產品在c

[0,12,3] 

我想這

index_list = [s.index(item) if item in b else s.index(item)+10 if item in c for item in s] 
print(index) 

但顯然這是一個語法錯誤。所以,我想這個

index_list = [s.index(item) if item in b else s.index(item)+10 for item in s if item in c] 
    print(index) 

輸出:

[12] 

這只是改變了整個邏輯。雖然我能做得到的本

fin = [s.index(item) if item in b else s.index(item)+10 if item in c else '' for item in s] 
fin = [item for item in fin if item!=''] 
print(fin) 

所需的輸出:

[0, 12, 3] 

但如何獲得我想要的清單理解本身或者是有什麼樣else continue在列表解析?任何解釋將不勝感激。

+0

我真的不明白你在這裏做什麼。 – Sam

+0

簡單地把像'[X,如果x在其他列表1 X + 10,如果x在列表2對於x在my_list]'這給一個語法錯誤。 – void

+0

我想要的東西,像'[X,如果x在其他列表1 X + 10,如果x在其他list2中傳爲X在my_list]'但是我知道,通過給語法錯誤。任何替代品? – void

回答

0
index_list = [s.index(item) if item in b else s.index(item) + 10 for item in s if item in b or item in c] 

,我們要確保它在B或C,則該指數將任何一種情況下

2

從根本上說,一個列表理解的力量,你是非常低效的:

>>> [i if item in b else i + 10 if item in c else None for i, item in enumerate(s) if item in b or item in c] 
[0, 12, 3] 

如果需要輸出,則必須檢查item中的成員bc兩次,每次最多兩次。相反,只需使用一個for循環

>>> index_list = [] 
>>> for i, item in enumerate(s): 
...  if item in b: 
...   index_list.append(i) 
...  elif item in c: 
...   index_list.append(i + 10) 
... 
>>> index_list 
[0, 12, 3] 
>>> 

簡單,可讀的,直接的和Python的。

0

您的解決方案故障可以通過避免在列表中不存在的元素來解決b & c。

你可以通過創建新的列表和應用簡單的設置操作

檢查解決方案中的這一變化不大做到這一點。

fin = [s.index(item) if item in b else s.index(item)+10 if item in c else '' for item in list(set(b+c)&set(s))] 

通過別人這樣做,你的conditinal語句永遠不會執行在其上迭代的原因只列出了一個元素,在任一列表bÇ只。

給出
0

已經很好的答案,這裏是一個還未被提及:

fin = [item for item in ([s.index(item) if item in b else s.index(item)+10 if item in c else '' for item in s]) if item!=''] 
print(fin) 

基本上是原來的2行代碼的組合:

fin = [s.index(item) if item in b else s.index(item)+10 if item in c else '' for item in s] 
fin = [item for item in fin if item!=''] 

不一定「更快或更好「,只是以前沒有給出的組合。 在進行列表推導時,您總是有可能會迭代超過實際需要的風險。

更好的解決方案將是一個for循環,這是另一個答案給出。

+0

如果你能解釋你的解決方案是如何工作的,它會比其他答案更好。僅有代碼的答案並不是非常有用。 – SiHa

+0

@SiHa;答案已更新。 –

+0

好多了,謝謝。 – SiHa