用另一个列表刷新Python中的列表内容
我想知道怎么把一个列表的内容扩展到另一个列表里,但不想用 .extend()
这个方法。我在想是不是可以用字典来实现。
代码
>>> 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]
3 个回答
0
如果你需要保持顺序的话,可以考虑用 OrderedDict 来代替 Counter:
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())
来获取键和值的列表。
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)
如果顺序不重要,那么有一种更简单的方法可以得到 out
和 iout
:
out = cnt.keys()
iout = cnt.values()
如果你不一定要使用一对列表,那么直接使用 Counter
就非常适合你的问题。
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})