【问题标题】:Python - How to create a new list and allocate a value based on certain mapping?Python - 如何创建一个新列表并根据特定映射分配一个值?
【发布时间】:2021-09-07 18:32:02
【问题描述】:

我应该如何使用 for 循环来实现以下目标?

目标:

  1. 结果将在新列表中返回 ---> 'z'
  2. “z”的长度与“y”的长度相同
  3. 如果 'y' 中的值等于 'v' 中的值,则返回共享 'v' 对应位置的 'x' 中的值

结果>>> z = [0.2, 0.2, 0.5, 0.5, 0.5, 0.3, 0.3, 0.3]

v = ['a', 'c', 'b']
x = [0.2, 0.3, 0.5]
y = ['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
z = []

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:
    1. 朴素方法
    z = []
    for item in y:
        # find index of item in 'v' list
        item_index = v.index(item)
        # get corresponding value in 'x' list
        value = x[item_index]
        # append in 'z' list
        z.append(value)
    
    1. 优化方式: 你制作一个字典,其中键来自“v”,值来自“x”列表,并迭代“y”列表并制作“z”列表
    search_dict = {}
    for i in range(len(v)):
        search_dict[v[i]] = x[i]
    
    z = []
    for item in y:
        if item in search_dict:
            z.append(search_dict[item])
    

    【讨论】:

    • 非常感谢,解释的很清楚了!
    【解决方案2】:
    for item in y:
      index = v.index(item)
      if index is not None:
        z.append(x[index])
      else:
        z.append(None)
    

    【讨论】:

    • 如果 'v' 是一个 numpy 数组而不是一个列表,我应该如何调整语法?
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多