python - 对列表进行操作并替换值

标签 python python-3.x list

我有一个名为'list_one'的列表,我试图将其与'list_relation'关联起来,最终得到一个最终的值列表,我的逻辑如下:

通过在'list_one'范围内循环,并针对'list_relation'中的每个'items_relation':

1.如果'list_one [i] [0]''items_relation'里面,我添加'list_one'的相应操作>.

list_one = [[1,      0], 
             [2,     0], 
             [3,     0],
             [4,     0], 
             [11,    0], 
             [12,    0], 
             [13, 2000], 
             [14, 3000], 
             [15, 3500], 
             [16, 5000], 
             [17, 6500], 
             [18, 8800], 
             [19, 6700],
             [20,  280]]

# Code to get this 'list_relation' ...

list_relation = [[13, 14], [15, 16], 
                 [17, 18], [19, 20]]
             
final = []
for i in range(len(list_one)):
    for items_elements in list_relation:
        for k in items_elements:
            if list_one[i][0] in items_elements:
                final.append((list_one[i][1] + list_one[i][0]))  
print(final)

我正在寻找这样的列表:

[[2013, 3014], [3515, 5016], [6517, 8818], [6719, 300]]

最好的方法是什么?谢谢。

最佳答案

list_one 似乎是一个查找表 - 使用字典而不是列表更有意义。然后循环遍历 list_relation 的值,对字典进行查找并添加该值(如果存在)。如果不存在,请获取默认值 0,这样它就不会影响总和。这也意味着不需要包含值为 0 的查找条目:

list_one = {13: 2000,  # note choose a better var name
            14: 3000, 
            15: 3500, 
            16: 5000, 
            17: 6500, 
            18: 8800, 
            19: 6700,
            20: 280,}

list_relation = [[13, 14], 
                 [15, 16], 
                 [17, 18], 
                 [19, 20]]

final = [[item + list_one.get(item, 0) 
          for item in pair] 
         for pair in list_relation]

关于python - 对列表进行操作并替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62825055/

相关文章:

python - 将 for 循环的数组结果存储在字典中

python - 使用 Numpy 计算相关系数

c++ - 如何执行与自身的快速合并 C++ 列表

python - subprocess.Popen 不执行 shell 脚本的所有行

python - 按列在 Pandas 数据框中选择一个随机值

python - OpenGL - 从不同角度渲染同一场景,无需重绘所有内容

python - celery 抛出 BacklogLimitExceeded

python - Google 安全浏览查找 API 中的请求无效

python - 合并numpy中的行以形成新数组

algorithm - 不要跳过列表具有与数组相同的限制?