【发布时间】:2017-05-02 15:53:30
【问题描述】:
我有以下元组列表:
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')。因此,我的问题是如何修复和更新元组的值(如果存在)?
【问题讨论】:
-
是否需要使用元组列表?元组是不可变的,因此如果我知道它们可能/将要更改,我不会使用它们。例如,也许您可以使用字典来存储映射,或者使用单独的列表来保持键的顺序?
-
@MxyL 不幸的是,元组是必要的......我也知道你的想法。
标签: python list python-3.x tuples list-comprehension