我正在撰寫一個程式,它可以在單獨的行中輸入三個數字和三個字母。然后程式會將數字分成串列的專案,并對單獨串列中的字母執行相同的操作。然后程式會將數字從低到高排序。然后我想將數字分配給字母(按排序的字母順序(IE A=5,B=16,C=20),然后按照輸入的順序列印字母(IE 輸入: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""")
想要/預期的輸入和輸出:
Input: "5 20 16"
Input: "CAB"
Output: "20 5 16"
uj5u.com熱心網友回復:
正如其他人所建議的那樣,您可能需要一個使用字典來查找給定字母的數字的答案。
##----------------------
## 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)
Will give us our lookup dictionary:
{
'A': '5',
'B': '16',
'C': '20'
}
Note that our zip() technically gives us back a list of tuples and we could also use dict() to cast them to our lookup.
lookup = dict(zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
))
print(lookup)
also gives us:
{
'A': '5',
'B': '16',
'C': '20'
}
But I'm not convinced that clarifies what is going on or not. It is the same result though so if you feel that is clearer go for it.
Now all we need to do is go back to our original input and take the letters one by one and feed them into our lookup to get back numbers.
Hope that helps.
uj5u.com熱心網友回復:
當您需要將字串轉換為變數時,這是非常奇怪的情況,當您覺得您需要類似的東西時,字典可能會解決問題。
在這種情況下,可以使用以下代碼完成解決方案。
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 超級快。
uj5u.com熱心網友回復:
您可以為此使用字典!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)
uj5u.com熱心網友回復:
使用 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426648.html
