3

我有一个格式的字典:

d[key] = [(val1, (Flag1, Flag2)),
          (val2, (Flag1, Flag2)),
          (val3, (Flag1, Flag2))]

我想做:

d[key] = [(val1, Flag1),
          (val2, Flag1),
          (val3, Flag1)]

我该怎么做?

4

3 回答 3

8

使用tuple解包:

d[key] = [(x, y) for (x, (y, z)) in d[key]]
于 2013-06-14T07:21:29.423 回答
2

应该适用于所有项目:

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

于 2013-06-14T07:25:01.943 回答
1

这应该这样做:

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。

于 2013-06-14T07:19:34.347 回答