我有以下格式的字典:d[key] = [(val1, (Flag1, Flag2)), (val2, (Flag1, Flag2)), (val3, (Flag1, Flag2))]我想做到:d[key] = [(val1, Flag1), (val2, Flag1), (val3, Flag1)]我该怎么做?
3 回答
LEATH
TA贡献1936条经验 获得超6个赞
这应该做到这一点:
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上都可以使用。
添加回答
举报
0/150
提交
取消