为变量名传递字符串 Python
Passing string for variable name Python
我正在编写一个程序,可以在不同的行中输入三个数字和三个字母。然后程序会将数字分成列表的项目,并将对单独列表中的字母执行相同的操作。然后程序将从最低到最高对数字进行排序。然后我想将数字分配给字母(按排序的字母顺序(即 A=5、B=16、C=20),然后按照输入的顺序打印字母(即输入:CAB,输出: 20 5 16)。我已经能够对变量进行排序,并且可以使用 if 语句和 for 循环来完成所有这些,但我觉得有一种更漂亮、更有效的方法可以做到这一点。我希望能够采用输入使用列表划分的字母字符串并格式化字符串以按正确顺序插入变量我知道 globals() 和 locals() 函数做类似的事情但无法弄清楚如何使用它们。有什么想法吗?
工作代码:
nput_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
print_string = ""
for i in range(3):
if input_letters[i] == "A":
print_string = print_string + A + " "
if input_letters[i] == "B":
print_string = print_string + B + " "
if input_letters[i] == "C":
print_string = print_string + C + " "
print(print_string)
我的(通缉)代码:
input_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
A = str(input_numbers_list[0])
B = str(input_numbers_list[1])
C = str(input_numbers_list[2])
final_list = ["""Magic that turns input_letters_list into variables in the order used by list and then uses that order"""]
print("{} {} {}".format("""Magic that turns final_list into variables in the order used by list and then puts it in string""")
Wanted/expected 输入输出:
Input: "5 20 16"
Input: "CAB"
Output: "20 5 16"
当您需要将字符串转换为变量时,当您觉得自己需要类似的东西时,字典可能就可以解决问题,这很奇怪。
在这种情况下,可以使用以下代码完成解决方案。
input_numbers_list = (("5 20 16").split(" "))
input_letters = ("CAB")
input_letters_list = [letter for letter in input_letters]
input_numbers_list = [int(x) for x in input_numbers_list]
rules = {}
for letter, value in zip(input_letters_list, input_numbers_list):
rules[value] = letter
output = ""
input_numbers_list.sort()
for numb in input_numbers_list:
output += rules[numb] + " "
print(output)
并且您可以将它用于 n 个输入和输出。
字典的想法是你有键和值,所以对于一个键(在本例中是字母文本)你可以得到一个值,类似于一个变量。 Plus超级快。
你可以使用字典! https://www.w3schools.com/python/python_dictionaries.asp
编辑:输出与请求的更一致,但如果我理解你的问题,它应该是“20 16 5”而不是“20 5 16”。
input_numbers_list = input().split(" ")
input_letters = input()
# Create new dictionary
input_dict = {}
# Fill it by "merging" both lists
for index, letter in enumerate(input_letters):
input_dict[letter] = input_numbers_list[index]
# Sort it by converting it into a list and riconverting to dict
sorted_dict = {k: v for k, v in sorted(list(input_dict.items()))}
# Print the result
output = ''
for value in sorted_dict.values():
output += value + ' '
print(output)
正如其他人所建议的,您可能需要一个使用字典来查找给定字母的数字的答案。
##----------------------
## hardcode your input() for testing
##----------------------
#input_numbers = input()
#input_letters = input()
input_numbers = "5 20 16"
input_letters = "CAB"
input_numbers_list = input_numbers.split(" ")
input_letters_list = list(input_letters) # not technically needed
##----------------------
##----------------------
## A dictionary comprehension
# used to construct a lookup of character to number
##----------------------
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
##----------------------
##----------------------
## use our original letter order and the lookup to produce numbers
##----------------------
result = " ".join(lookup[a] for a in input_letters_list)
##----------------------
print(result)
这将为您提供您请求的输出:
20 5 16
字典查找的构造有很多事情要做,所以让我们稍微解压一下。
首先,它是基于调用zip()
。此函数采用两个“列表”并将它们的元素配对以创建一个新的“列表”。我在引号中使用“列表”,因为它更像是可迭代对象和生成器。无论如何。让我们仔细看看:
list(zip(["a","b","c"], ["x","y","z"]))
这会给我们:
[
('a', 'x'),
('b', 'y'),
('c', 'z')
]
这就是我们将数字和字母成对组合在一起的方式。
但在我们这样做之前,重要的是要确保我们要将“最大”的字母与“最大”的数字配对。为确保我们将获得两个列表的排序版本:
list(
zip(
sorted(input_letters_list), #ordered by alphabet
sorted(input_numbers_list, key=int) #ordered numerically
)
)
给我们:
[
('A', '5'),
('B', '16'),
('C', '20')
]
现在我们可以将其输入到我们的词典理解中 (https://docs.python.org/3/tutorial/datastructures.html)。
这将构建一个字典,其中包含上述 zip() 中字母的键和数字的值。
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
print(lookup)
会给我们查找字典:
{
'A': '5',
'B': '16',
'C': '20'
}
请注意,我们的 zip()
在技术上给了我们一个元组列表,我们也可以使用 dict()
将它们转换为我们的查找。
lookup = dict(zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
))
print(lookup)
也给了我们:
{
'A': '5',
'B': '16',
'C': '20'
}
但我不相信这说明了正在发生或没有发生的事情。这是相同的结果,所以如果你觉得更清楚,那就去吧。
现在我们需要做的就是返回到我们的原始输入,一个接一个地输入字母并将它们输入到我们的查找中以获取返回的数字。
希望对您有所帮助。
使用 zip 功能有帮助
num_arr = list(map(int,input().split(' ')))
word = input()
num_arr.sort()
word = sorted(word)
mapper = dict(zip(word,num_arr))
result = ' '.join(map(str,[mapper[i] for i in word]))
print(result)
我正在编写一个程序,可以在不同的行中输入三个数字和三个字母。然后程序会将数字分成列表的项目,并将对单独列表中的字母执行相同的操作。然后程序将从最低到最高对数字进行排序。然后我想将数字分配给字母(按排序的字母顺序(即 A=5、B=16、C=20),然后按照输入的顺序打印字母(即输入:CAB,输出: 20 5 16)。我已经能够对变量进行排序,并且可以使用 if 语句和 for 循环来完成所有这些,但我觉得有一种更漂亮、更有效的方法可以做到这一点。我希望能够采用输入使用列表划分的字母字符串并格式化字符串以按正确顺序插入变量我知道 globals() 和 locals() 函数做类似的事情但无法弄清楚如何使用它们。有什么想法吗?
工作代码:
nput_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
print_string = ""
for i in range(3):
if input_letters[i] == "A":
print_string = print_string + A + " "
if input_letters[i] == "B":
print_string = print_string + B + " "
if input_letters[i] == "C":
print_string = print_string + C + " "
print(print_string)
我的(通缉)代码:
input_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
A = str(input_numbers_list[0])
B = str(input_numbers_list[1])
C = str(input_numbers_list[2])
final_list = ["""Magic that turns input_letters_list into variables in the order used by list and then uses that order"""]
print("{} {} {}".format("""Magic that turns final_list into variables in the order used by list and then puts it in string""")
Wanted/expected 输入输出:
Input: "5 20 16"
Input: "CAB"
Output: "20 5 16"
当您需要将字符串转换为变量时,当您觉得自己需要类似的东西时,字典可能就可以解决问题,这很奇怪。
在这种情况下,可以使用以下代码完成解决方案。
input_numbers_list = (("5 20 16").split(" "))
input_letters = ("CAB")
input_letters_list = [letter for letter in input_letters]
input_numbers_list = [int(x) for x in input_numbers_list]
rules = {}
for letter, value in zip(input_letters_list, input_numbers_list):
rules[value] = letter
output = ""
input_numbers_list.sort()
for numb in input_numbers_list:
output += rules[numb] + " "
print(output)
并且您可以将它用于 n 个输入和输出。
字典的想法是你有键和值,所以对于一个键(在本例中是字母文本)你可以得到一个值,类似于一个变量。 Plus超级快。
你可以使用字典! https://www.w3schools.com/python/python_dictionaries.asp
编辑:输出与请求的更一致,但如果我理解你的问题,它应该是“20 16 5”而不是“20 5 16”。
input_numbers_list = input().split(" ")
input_letters = input()
# Create new dictionary
input_dict = {}
# Fill it by "merging" both lists
for index, letter in enumerate(input_letters):
input_dict[letter] = input_numbers_list[index]
# Sort it by converting it into a list and riconverting to dict
sorted_dict = {k: v for k, v in sorted(list(input_dict.items()))}
# Print the result
output = ''
for value in sorted_dict.values():
output += value + ' '
print(output)
正如其他人所建议的,您可能需要一个使用字典来查找给定字母的数字的答案。
##----------------------
## hardcode your input() for testing
##----------------------
#input_numbers = input()
#input_letters = input()
input_numbers = "5 20 16"
input_letters = "CAB"
input_numbers_list = input_numbers.split(" ")
input_letters_list = list(input_letters) # not technically needed
##----------------------
##----------------------
## A dictionary comprehension
# used to construct a lookup of character to number
##----------------------
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
##----------------------
##----------------------
## use our original letter order and the lookup to produce numbers
##----------------------
result = " ".join(lookup[a] for a in input_letters_list)
##----------------------
print(result)
这将为您提供您请求的输出:
20 5 16
字典查找的构造有很多事情要做,所以让我们稍微解压一下。
首先,它是基于调用zip()
。此函数采用两个“列表”并将它们的元素配对以创建一个新的“列表”。我在引号中使用“列表”,因为它更像是可迭代对象和生成器。无论如何。让我们仔细看看:
list(zip(["a","b","c"], ["x","y","z"]))
这会给我们:
[
('a', 'x'),
('b', 'y'),
('c', 'z')
]
这就是我们将数字和字母成对组合在一起的方式。
但在我们这样做之前,重要的是要确保我们要将“最大”的字母与“最大”的数字配对。为确保我们将获得两个列表的排序版本:
list(
zip(
sorted(input_letters_list), #ordered by alphabet
sorted(input_numbers_list, key=int) #ordered numerically
)
)
给我们:
[
('A', '5'),
('B', '16'),
('C', '20')
]
现在我们可以将其输入到我们的词典理解中 (https://docs.python.org/3/tutorial/datastructures.html)。
这将构建一个字典,其中包含上述 zip() 中字母的键和数字的值。
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
print(lookup)
会给我们查找字典:
{
'A': '5',
'B': '16',
'C': '20'
}
请注意,我们的 zip()
在技术上给了我们一个元组列表,我们也可以使用 dict()
将它们转换为我们的查找。
lookup = dict(zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
))
print(lookup)
也给了我们:
{
'A': '5',
'B': '16',
'C': '20'
}
但我不相信这说明了正在发生或没有发生的事情。这是相同的结果,所以如果你觉得更清楚,那就去吧。
现在我们需要做的就是返回到我们的原始输入,一个接一个地输入字母并将它们输入到我们的查找中以获取返回的数字。
希望对您有所帮助。
使用 zip 功能有帮助
num_arr = list(map(int,input().split(' ')))
word = input()
num_arr.sort()
word = sorted(word)
mapper = dict(zip(word,num_arr))
result = ' '.join(map(str,[mapper[i] for i in word]))
print(result)