2015-11-14 78 views
1

我已經列出了一些文字,另一個列表只包含了需要的文字,我想用相關文字和它們的符號得到輸出,應該如何我計算這個輸出?非常感謝編輯一個列表,同時將它與另一個列表作爲約束條件進行比較

list=[0,-1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30] 

needed literals = [11, 12, 13, 21, 22, 23, 31, 32, 33] 

output = [11, 12, -13, 21, -22, 23, 31, -32, 33] 

編輯:文本中的每一個也是一個字符串,如:「11」,「-12」等

回答

2

這是一個列表理解很容易:

literal_list = [0, -1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30] 
needed_literals = [11, 12, 13, 21, 22, 23, 31, 32, 33] 
output = [n for n in literal_list if abs(n) in needed_literals] 
#=> [11, 12, -13, 21, -22, 23, 31, -32, 33] 

如果兩個列表的元素是字符串而不是整數,你可以在條件轉換:

output = [n for n in literal_list if str(abs(int(n))) in needed_literals] 
0
lis=[0,-1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30] 

literals = [11, 12, 13, 21, 22, 23, 31, 32, 33] 

output=[] 
li=0 
i=0 
for i in range(0,len(lis)-1): 
    if mod(literals[li])==lis[i]: 
     output.append(lis[i]) 
     li+=1 
    i+=1 
print output 
0
input_list=[0,-1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30] 
needed_literals = [11, 12, 13, 21, 22, 23, 31, 32, 33] 

隨着重複:

output = [ for i in input_list if abs(i) in needed_literals] 

沒有重複:

output = [ for i in set(input_list) if abs(i) in needed_literals] 
相關問題