我想知道如何遍历多个列表,将值与字典中的键匹配,然后创建一个等于值的新列表。
我是Stack和Python的新手,所以将不胜感激。
X1 = [1, 2, 3, 5, 4]
X2 = [3, 2, 2, 5, 1]
X3 = [2, 4, 3, 1, 5]
Y1 = []
Y2 = []
Z = {1:20, 2:19, 3:18, 4:17, 5:16}
def num_maker(num_list, new_list):
for nums in num_list:
if nums in Z.iterkeys():
for newnums in new_list:
new_list = Z.value(nums)
num_maker(X1, Y1)
如果您有兴趣学习如何在没有@Joachim Isaksson提供的列表理解的情况下进行此操作
这是您需要做的:
# Your number list
X1 = [1, 2, 3, 5, 4]
# Your dictionary with keys from the number list
Z = {1:20, 2:19, 3:18, 4:17, 5:16}
# Expected output list should be: [20,19,18,16,17] based on X1
def num_maker(num_list, dictionary_of_num_list):
# Initialize empty list
list_to_return = []
# Loop over your num_list
for number in num_list:
# Access the dictionary using the list's current element as the key and then append it to a new list which you can return
list_to_return.append(dictionary_of_num_list.get(number))
return list_to_return
print(num_maker(X1, Z))
输出:
[20, 19, 18, 16, 17]
您希望将Y1作为输出列表,因此您可以这样做:
Y1 = num_maker(X1, Z)
希望这可以帮助。使用python 3而不是python 2运行它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句