如何更改元组列表的某些值?

时间:2016-12-16 19:38:11

标签: python list python-3.x tuples list-comprehension

我有以下元组列表:

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')。因此,我的问题是如何修复和更新元组的值(如果它们存在?)。

2 个答案:

答案 0 :(得分:2)

使用列表推导来重建列表

line = "I like to play guitar and piano and drums"
words = line.split()
letters = [word[0] for word in words]
print "".join(letters)

这会覆盖tags = {'google': 'entity', 'iphone': 'device', ...} lis = [(a, tags[a.lower()]) if a.lower() in tags else (a, b) for a, b in lis] 之类的元组,也就是说它并不关心第二个变量中的内容。

答案 1 :(得分:1)

如果您需要更改此位置并且已经具有替换它们所需的值,我只需在替换字段中创建字典然后替换:

package