2016-03-03 33 views
-4

如果我有3個表是這樣的:如何比較列表在Python

general_list = ['P' ,  'J' , 'C', 'H' ,  'O'] 

real_list = ['Python', 'Java' , 'C' , 'Html' , 'Other'] 

,並呼籲其他列表

selected_items = [ 'Python' , 'Php'] 

我想selected_itemsreal_list比較,所以我可以有當結果元素在列表0 or 1,所以我想要做這樣的事情:[ 1 , 0 , 0, 0 , 1] 然後檢查general_list中的項目何時被選中並得到如下結果['P' , 'O']

我真的不知道該怎麼做?

+4

什麼嘗試到目前爲止? – MSeifert

+0

應該試一試嗎?鉛筆和紙張會是一個好的開始? –

+0

@MSeifert我只是不知道從哪裏開始,所以爲此我詢問了任何想法,因爲我不想讓別人爲我編碼,只是給我一個提示 – EgzEst

回答

0

您可以用兩個列表內涵做到這一點:

inlist = [True if x in selected_items else False for x in real_list] 
result = [v for i, v in enumerate(general_list) if inlist[i]] 
1

好像一個XY problem。如果你真正想要的是用selected_items來獲得最終結果,那麼:

this_is_useful = {'Python': 'P', 'Java': 'J', 'C': 'C', 'Html': 'H'} 

然後,你可以通過做

if 'Python' in this_is_useful: 
    print "Yes!" 

檢查'Python'屬於要獲得最終結果:

selected_items = [ 'Python' , 'Php' ] 
result = [this_is_useful.get(l, 'O') for l in selected_items]