如何用字典中对应的数字替换列表中的数字?

2024-05-08 00:42:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何用字典中对应的数字替换列表中的数字的正确方法。你知道吗

目前我的代码是:

#the object list and max weight are supposed to be user input but i have hard coded it in for now to try and get other parts working first.

object_list = [(2, 70), (3, 85), (5, 120)] # the first number in the tuple is my weight and the second is my cost

max_weight = 17 #this is the number each list in the list of lists add to 

#seperatng weights and costs into a string then making a dictionary out of it.
weight_values = [int(i[0]) for i in object_list] 
cost_values = [int(i[1]) for i in object_list]
dictionary = dict(zip(weight_values, cost_values))

假设我有一个列表(添加到最大重量的所有可能的组合):

[[3, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 2, 2, 2, 2], [3, 3, 3, 3, 3, 2], [5, 2, 2, 2, 2, 2, 2], [5, 3, 3, 2, 2, 2], [5, 3, 3, 3, 3], [5, 5, 3, 2, 2], [5, 5, 5, 2]]

我生成的字典是:

dictionary = {2: 70, 3: 85, 5: 120}

我想尝试做的是用70替换所有的2,用85替换所有的3,用120替换所有的5(对于这个例子)。生成的字典是基于用户输入的,因此在另一个场景中,所有的2可能需要替换为35而不是70。我需要一种方法来替换数字,而不需要特别说明,比如如果有2,就用70替换。此列表列表是使用此答案(Recursive tree terminates function prematurely)生成的


Tags: andthetoin列表fordictionary字典
2条回答

要替换列表中的值:

l = [[3, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 2, 2, 2, 2], [3, 3, 3, 3, 3, 2], [5, 2, 2, 2, 2, 2, 2], [5, 3, 3, 2, 2, 2], [5, 3, 3, 3, 3], [5, 5, 3, 2, 2], [5, 5, 5, 2]]
dictionary = {2: 70, 3: 85, 5: 120}
new_l = [[dictionary[b] for b in i] for i in l]

输出:

[[85, 70, 70, 70, 70, 70, 70, 70], [85, 85, 85, 70, 70, 70, 70], [85, 85, 85, 85, 85, 70], [120, 70, 70, 70, 70, 70, 70], [120, 85, 85, 70, 70, 70], [120, 85, 85, 85, 85], [120, 120, 85, 70, 70], [120, 120, 120, 70]]

要替换值:

old_list = [[3, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 2, 2, 2, 2], [3, 3, 3, 3, 3, 2], [5, 2, 2, 2, 2, 2, 2], [5, 3, 3, 2, 2, 2], [5, 3, 3, 3, 3], [5, 5, 3, 2, 2], [5, 5, 5, 2]]
dictionary = {2: 70, 3: 85, 5: 120}
new_list = []
temp = []
for i in old_list:
    temp = []
    for b in i:
        temp.append(dictionary[b])
    new_list.append(temp)

输出:

[[85, 70, 70, 70, 70, 70, 70, 70], [85, 85, 85, 70, 70, 70, 70], [85, 85, 85, 85, 85, 70], [120, 70, 70, 70, 70, 70, 70], [120, 85, 85, 70, 70, 70], [120, 85, 85, 85, 85], [120, 120, 85, 70, 70], [120, 120, 120, 70]]

相关问题 更多 >