2016-12-16 118 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])