【问题标题】:How to change a tuple within a value of a dictionary?如何更改字典值中的元组?
【发布时间】:2013-06-10 18:51:19
【问题描述】:

我有一本格式如下的字典:

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

我想做:

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

我该怎么做?

【问题讨论】:

    标签: python dictionary tuples


    【解决方案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。

    【讨论】:

    • 你能解释一下吗?
    • 对所有键值对都适用吗?
    • @IndradhanushGupta 通知 (x, val[0]) , val[1] 在列表压缩中被丢弃。
    • @GrijeshChauhan 它会对所有键值对都这样做吗?
    • @IndradhanushGupta 它没有。如果您想对所有键执行此操作,请将该行包装在循环所有键的 for 循环中。
    【解决方案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

    【讨论】:

      【解决方案3】:

      使用tuple解包:

      d[key] = [(x, y) for (x, (y, z)) in d[key]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        • 2020-12-16
        • 1970-01-01
        • 2021-11-26
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多