【问题标题】:How do I replace a value in a matrix which corresponding to another matrix?如何替换矩阵中对应于另一个矩阵的值?
【发布时间】:2018-11-19 02:16:43
【问题描述】:

例如

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

我想得到一个矩阵c:

c = [0.5, 0.8, 0, 0.11, 0, 0]

这就像如果a中的i = ww for ww,ee in n for n in b,则替换为ee else 0

我尝试了一些 if 和 else 命令,这是我的代码

for n in b:
for t,y in n:
    for tt in a:
        mmm = [y if t == ''.join(tt) else ''.join(tt)]
        print(mmm)

但它失败了。我应该如何针对这种情况编写代码?

【问题讨论】:

  • c 中的最后一个值不应该是0.23 吗?
  • [dict(sum(b,[])).get(int(i),0) for i in a]

标签: python python-3.x numpy if-statement replace


【解决方案1】:

chain + dict + 列表理解

您的b 映射是一个列表列表,您可以通过chain.from_iterable 将其展平为一个可迭代的元组。然后反馈给dict 以创建高效的映射。

最后,使用带有dict.get 的列表推导式来获得所需的结果。请记住将a 的值从str 转换为int

from itertools import chain

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

b_dict = dict(chain.from_iterable(b))
c = [b_dict.get(i, 0) for i in map(int, a)]

print(c)

[0.5, 0.8, 0, 0.11, 0, 0.23]

【讨论】:

    【解决方案2】:

    这将遍历列表a,将其值与b 列表中元组的第一个值进行比较。如果 tuple 的第一个值与 a 中的值匹配,则这会将 tuple 的第二个值附加到输出列表:

    from itertools import chain
    
    a = ['1', '2', '3', '4', '5', '6']
    b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]
    
    b = list(chain.from_iterable(b))
    lst = []
    for x in a:
        for y, z in b:
            if y == int(x):
                lst.append(z)
                break
        else:
            lst.append(0)
    
    print(lst)
    # [0.5, 0.8, 0, 0.11, 0, 0.23]
    

    【讨论】:

      【解决方案3】:

      您可以将映射的双重列表转换为查找字典并使用 list-comp:

      a = ['1', '2', '3', '4', '5', '6']
      b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]
      
      # convert b to a dictionary:
      d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value 
      print(d)
      
      # apply the lookup to a's values
      result = [d.get(k,0) for k in a]
      print(result)
      

      输出:

      # the lookup-dictionary
      {'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}
      
      # result of list c,omprehension
      [0.5, 0.8, 0, 0.11, 0, 0.23]
      

      相关:

      【讨论】:

        猜你喜欢
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 2016-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        相关资源
        最近更新 更多