我有一个名为'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/