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

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

最佳答案

使用列表理解来重建列表

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/

相关文章:

python - Python 中基于分隔符分割和组合文本

python - 为什么输出总是为零?

list - 如何检查一个数字是否在列表中的另一个数字之前

python - 将 Array_list 值插入另一个空 Array_list

python-3.x - scikit-learn 中针对大量特征的特征选择

python - Python 程序在 PyCharm 中运行后,Tkinter 窗口自动关闭

python - 为什么我的python for循环冒号会出现语法错误?

python - 无法使用pip安装pyinstaller

python - 如何从列表中解压四个变量?

python - 如何将异步 on_message 函数与 python web 套接字客户端库一起使用?