我有以下元组列表:
lis = [('The', 'DET'),
('iphone', 'X'),
('is', 'VERB'),
('a', 'DET'),
('very', 'ADV'),
('nice', 'ADJ'),
('device', 'NOUN'),
('.', 'PUNCT'),
('However', 'ADP'),
('the', 'DET'),
('pixel', 'X'),
('is', 'VERB'),
('by', 'ADP'),
('far', 'ADV'),
('more', 'ADV'),
('interesting', 'ADJ'),
('since', 'ADV'),
('it', 'PRON'),
('was', 'AUX'),
('made', 'VERB'),
('by', 'ADP'),
('google', 'NOUN'),
('.', 'PUNCT')]
我的主要目标是专门更改此元组的值:('iphone', 'X'), ('pixel', 'X'), ('google', 'NOUN')
到 ('iphone', 'device'), ('pixel', 'device'), ('google', 'entity')
。因此,由于我对保留顺序感兴趣,因此我尝试了以下操作:
tags['Google'] = 'device'
tags['pixel'] = 'device'
tags['iphone'] = 'entity'
#this one is not present in lis . Nevertheless, I would like to add it just in case I need it.
tags['galaxy'] = 'device'
tags = list(tags.items())
tags = OrderedDict(postag(str(sample)))
自从我添加 tags['galaxy'] = 'device'
后,它实际上将其添加到列表的末尾 ('galaxy', 'device')
。因此,我的问题是如何修复和更新元组的值(如果存在)?
最佳答案
使用列表理解来重建列表
tags = {'google': 'entity', 'iphone': 'device', ...}
lis = [(a, tags[a.lower()]) if a.lower() in tags else (a, b) for a, b in lis]
这将覆盖像 ('iphone', 'something')
这样的元组,也就是说它不关心第二个变量中的内容。
关于python - 如何更改元组列表的某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41191373/