【发布时间】:2016-07-21 14:23:04
【问题描述】:
我有 2 个键值对字典,例如:
tokenIDs2number = {(6, 7): 1000000000.0, (22,): 700.0, (12,): 3000.0}
tokenIDs2number = {(27, 28): u'South Asia'}
key 是句子中 number 和 location slots 的索引位置的元组:
GDP in 2007 totaled about $ 1 billion , or about $ 3,000 per capita -LRB- exceeding the average of about $ 700 in the rest of South Asia -RRB- .
我想遍历数字和位置的所有元组,如果它们彼此相邻,则从元组中删除值,例如制作它们:
tokenIDs2number = {(7,): 1000000000.0, (22,): 700.0, (12,): 3000.0}
tokenIDs2number = {(28,): u'South Asia'}
这样以后,我可以用位置和数字槽填充这个句子标记,所以句子变成:
GDP in 2007 totaled about $ NUMBER_SLOT , or about $ NUMBER_SLOT per capita -LRB- exceeding the average of about $ NUMBER_SLOT in the rest of LOCATION_SLOT -RRB- .
代替:
GDP in 2007 totaled about $ NUMBER_SLOT NUMBER_SLOT , or about $ NUMBER_SLOT per capita -LRB- exceeding the average of about $ 700 in the rest of LOCATION_SLOT LOCATION_SLOT -RRB- .
当前代码:
for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
prevNoID=numberTokenIDs[0]
prevLocID=locationTokenIDs[0]
for numberTokenID in numberTokenIDs:
for locationTokenID in locationTokenIDs:
if numberTokenID==prevNoID+1:
numberTokenIDs.remove(numberTokenIDs[prevNoID])
if numberTokenID>0 and numberTokenID<(len(sampleTokens)-1):
prevNoID = numberTokenID
if locationTokenID==prevLocID+1:
locationTokenIDs.remove(locationTokenIDs[prevLocID])
if locationTokenID>0 and locationTokenID<(len(sampleTokens)-1):
prevLocID = locationTokenID
但是,我似乎不能只从元组中删除数字,所以我正在努力弄清楚如何做到这一点。
【问题讨论】:
-
元组是不可变的,你试过用列表吗?
-
@Yegers 不能使用列表作为键。它们是可变的,因此不能有意义地散列,因此实际上不是可散列的。 dicts 使用哈希来存储东西。
标签: python dictionary tuples