2013-03-15 134 views
1

如何在不使用方法.extend()的情況下將給定列表的內容與另一個給定列表進行擴展?我想我可以用字典的東西。使用Python中的另一個列表刷新列表內容

代碼

>>> tags =['N','O','S','Cl'] 
>>> itags =[1,2,4,3] 

>>> anew =['N','H'] 
>>> inew =[2,5] 

我需要它返回刷新列表

tags =['N','O','S','Cl','H'] 
itags =[3,2,4,3,5] 

當一個元素已經在列表中,被添加在其他列表中的號碼的功能。如果我使用extend()法,元素N將出現在列表tags兩次:

>>> tags.extend(anew) 
>>>itags.extend(inew) 
>>> print tags,itags 
    ['N','O','S','Cl','N','H'] [1,2,4,3,5,2,5] 
+0

我們能否推測'tags'中的元素是唯一的?訂單是否重要(除了將'tag'匹配到'itags')? – 2013-03-15 18:56:21

+0

爲什麼itag有兩個3和1? – Hoopdady 2013-03-15 18:56:51

+0

我不明白你是如何得到新的'itags'。 '1'去哪了,爲什麼在開始時會出現'3'? – poke 2013-03-15 18:57:07

回答

4

你可能想爲這個Counter

from collections import Counter 
tags = Counter({"N":1, "O":2, "S": 4, "Cl":3}) 
new = Counter({"N": 2, "H": 5}) 

tags = tags + new 
print tags 

輸出:

Counter({'H': 5, 'S': 4, 'Cl': 3, 'N': 3, 'O': 2}) 
+2

爲了生成'Counter'需要的字典,OP可以使用'dict(zip(tags,itags))'。 – DSM 2013-03-15 19:01:11

+0

謝謝大家!我不知道這個圖書館的藏品。很有用! – 2013-03-15 19:48:54

1

如果元素的順序很重要,我會使用collections.Counter像這樣:

from collections import Counter 

tags = ['N','O','S','Cl'] 
itags = [1,2,4,3] 

new = ['N','H'] 
inew = [2,5] 

cnt = Counter(dict(zip(tags, itags))) + Counter(dict(zip(new, inew))) 
out = tags + [el for el in new if el not in tags] 
iout = [cnt[el] for el in out] 

print(out) 
print(iout) 

如果順序並不重要,還有一個更簡單的方法獲得outiout

out = cnt.keys() 
iout = cnt.values() 

如果您沒有使用一對清單,那麼直接與Counter合作對您的問題來說是非常合適的。

+0

如果順序很重要,如果不是,那麼最好的選擇是將它保留爲'Counter()'並且有一個更合適的數據結構。 – 2013-03-15 19:01:21

0

如果你需要維持秩序,您可能需要使用的,而不是一個計數器的OrderedDict:

from collections import OrderedDict 

tags = ['N','O','S','Cl'] 
itags = [1,2,4,3] 

new = ['N','H'] 
inew = [2,5] 

od = OrderedDict(zip(tags, itags)) 
for x, i in zip(new, inew): 
    od[x] = od.setdefault(x, 0) + i 

print od.keys() 
print od.values() 

Python的3.x中,使用list(od.keys())list(od.values())

+0

使用「櫃檯」,然後在NPE的回答中引入訂單也保持秩序。 – 2013-03-15 19:11:13

+0

的確如此,但我認爲手動處理計數比排序更直接。如果重複進行,效率也會更高。 – 2013-03-15 19:18:51

相關問題