是否確實需要這樣的輸出:d = { 'A':0, 'B':1, 'C':2, '1':3, '2':4,「3 ':5}而不是D = {0:'A',1:'B',2:'C'...}?你可以翻轉鍵:值,但它們將是無序的(例如,你會得到類似於:D = {'B':1,'3':5,'A':0,'C':2'' 1':3,'2':4}或任何其他隨機組合)。
這聽起來像你正在開始學習python。歡迎使用漂亮的編程語言。人們在這裏非常有幫助,但你需要表現出一些努力和主動。這不是獲得快速解決方案的地方。人們可能會提供給你,但你永遠不會學習。
我認爲這是一個與HW有關的問題?除非我錯了(某人請隨時糾正我),否則您所尋找的輸出即使不是不可能創建(例如按照您想要的特定順序)也很困難。我鼓勵你閱讀python dictionaries。
嘗試運行此:
#user = input("Give me a string:")
#Just for demo purpose, lets
#stick with your orig example
user = "ABC123"
ls =[] #create empty list
d = {} #create empty dictionary
#Try to figure out and understand
#what the below code does
#what is a list, tuple, dict?
#what are key:values?
for l in enumerate(user):
ls.append(l)
for k,v in ls:
d[k] = v
print('first code output')
print(ls)
print(d)
#What/how does enumerate work?
#the below will generate a
#ordered dict by key
for k,v in enumerate(user):
d[k] = v
print('2nd code output')
print(d)
#you want to flip your key:value
#output, bases on origibal question
#notice what happens
#run this a few times
print('3rd code output')
print(dict(zip(d.values(), d.keys())))
#You can get the order you want,
#but as a list[(tuple)], not as
#a dict at least in the output
#from your orig question
print(list(zip(d.values(), d.keys())))
除非我錯了,而且更有經驗的人可以插話,你不能讓你想爲你的詞典中的格式「命令」的輸出。
我在移動設備上,所以任何人請隨時糾正的事情。
歡迎來到[so]。不要粗魯,但作爲志願者,我們的幫助不是由於你的時間緊迫。請檢查[問]並嘗試。我們不是來爲你做功課的。 – TemporalWolf
如果輸入是「AA」,預期的輸出是多少? – Goyo
期望輸出將是d = {'A':0,'A':1} 另外,對於我如何表達我的問題感到抱歉。並不是想讓它看起來像這樣。我現在編輯它。 – garow93