![](/img/trans.png)
[英]How to return maximum of value in a tuple within a list within a dictionary?
[英]How to change a tuple within a value of a dictionary?
我有一個格式的字典:
d[key] = [(val1, (Flag1, Flag2)),
(val2, (Flag1, Flag2)),
(val3, (Flag1, Flag2))]
我想做到:
d[key] = [(val1, Flag1),
(val2, Flag1),
(val3, Flag1)]
我該怎么做?
使用tuple
解包:
d[key] = [(x, y) for (x, (y, z)) in d[key]]
應該適用於所有項目:
d = { k: [(x, y) for (x, (y, z)) in v] for k,v in d.iteritems() }
您可能需要閱讀: http : //docs.python.org/2/tutorial/datastructures.html#list-comprehensions
這應該這樣做:
d[key] = [(x, y[0]) for x,y in d[key]]
簡單版本:
new_val = []
for x, y in d[key]:
#In each iteraion x is assigned to VALs and `y` is assigned to (Flag1, Flag2)
#now append a new value, a tuple containg x and y[0](first item from that tuple)
new_val.append((x, y[0]))
d[key] = new_val #reassign the new list to d[key]
要修改整個字典:
dic = { k: [(x, y[0]) for x,y in v] for k,v in dic.items()}
在py2.x中,你可以使用dic.iteritems
因為它返回一個迭代器, dic.items()
將在py2x和py3x上工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.