2017-10-13 201 views
-1

實現以下目標的pythonic方式是什麼?元組的合併列表

來自:

l1 = ([('ADJ', 29), ('CONJ', 1), ('PRT', 2), ('X', 3), ('ADV', 18), ('VERB', 52), ('ADP', 1), ('NOUN', 27)]) 
l2 = ([('ADJ', 312), ('INTJ', 2), ('ADP', 5), ('PART', 6), ('DET', 2), ('ADV', 323), ('VERB', 1196), ('NOUN', 1162)]) 

到:

l3 = ([('ADJ', 312,29), ('ADP', 5,1), ('ADV', 323,18), ('VERB', 1196,52), ('NOUN', 1162,27)]) 
+3

顯示您的嘗試,它的拼寫'元組' –

回答

1

你可以試試這個:

l1 = ([('ADJ', 29), ('CONJ', 1), ('PRT', 2), ('X', 3), ('ADV', 18), ('VERB', 52), ('ADP', 1), ('NOUN', 27)]) 
l2 = ([('ADJ', 312), ('INTJ', 2), ('ADP', 5), ('PART', 6), ('DET', 2), ('ADV', 323), ('VERB', 1196), ('NOUN', 1162)]) 
d1 = dict(l1) 
d2 = dict(l2) 
new_data = tuple([(c, d1[c], d2.get(c, None)) for c in d1])  
final_data = list(filter(lambda x:len(x) > 2, tuple(map(tuple, tuple([(b for b in i if b is not None) for i in new_data]))))) 

輸出:

[('ADV', 18, 323), ('NOUN', 27, 1162), ('ADP', 1, 5), ('VERB', 52, 1196), ('ADJ', 29, 312)] 
0

我的意思是,你可以這樣做:

result = [(a, b, d) for (a, b), (c, d) in zip(l1, l2)]

我相信會做什麼你問(但我目前無法測試)

+1

劃痕,我只是注意到你的列表沒有相同的元素 – user2662833

0

我不知道Python有這樣的一個襯墊,但你可以做的是使用字典合併兩個列表。

l1 = ([('ADJ', 29), ('CONJ', 1), ('PRT', 2), ('X', 3), ('ADV', 18), ('VERB', 52), ('ADP', 1), ('NOUN', 27)]) 
l2 = ([('ADJ', 312), ('INTJ', 2), ('ADP', 5), ('PART', 6), ('DET', 2), ('ADV', 323), ('VERB', 1196), ('NOUN', 1162)]) 
d2 = dict(l2) 

#Merge l1 and d2 
result = [(k, v, d2[k]) for k, v in l1]