2016-12-16 105 views
1

我的元组下面的列表:如何更改元组列表的值?

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

+0

是否有必要使用元组列表?元组是不可改变的,所以设计我不会使用它们,如果我知道它们可能会改变。例如,也许你可以使用字典来存储映射,也可以使用单独的列表来保存键的顺序? – MxyL

+0

@MxyL不幸的是,元组是必要的...我也想出你的想法。 –

回答

1

使用列表理解来重建列表像('iphone', 'something')

tags = {'google': 'entity', 'iphone': 'device', ...} 

lis = [(a, tags[a.lower()]) if a.lower() in tags else (a, b) for a, b in lis] 

这将覆盖元组,也就是说它不关心什么是在第二个变量。

+0

如果它们不存在于我的文本中呢?理解列表是否足够健壮以处理这个问题,而不是添加它们? –

+1

这个列表理解不会把'lis'中的值放到那里。一些阅读列表解析:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions –

+0

我得到了:'ValueError:太多的值来解压(预计2)' –

1

如果您需要更改这个地方,已经有你需要更换他们的价值观,我想简单地创建一个字典出替换字段,然后替换:

rep = dict([('iphone', 'device'), ('pixel', 'device'), ('google', 'entity')]) 

for ind, (i, j) in enumerate(lis): 
    if i in rep: 
     lis[ind] = (i, rep[i])