2017-03-31 140 views
-3

在我身後有一個python類,我在下一節課中被提出這個問題,而且我似乎對如何開始有一個心理障礙。將字符串轉換成字典

「編寫一個python程序,要求用戶輸入一個字符串,然後創建下列字典:值是字符串中的字母,相應的鍵是字符串中的位置。字符串「ABC123」,則字典將是:D = {'A':0,'B':1,'C':2,'1':3,'2':4,'3':5}

我開始用要求用戶輸入與像

s = input('Enter string: ') 
然而

簡單的東西,我不知道如何進行下一步。任何幫助,將不勝感激。

+0

歡迎來到[so]。不要粗魯,但作爲志願者,我們的幫助不是由於你的時間緊迫。請檢查[問]並嘗試。我們不是來爲你做功課的。 – TemporalWolf

+1

如果輸入是「AA」,預期的輸出是多少? – Goyo

+0

期望輸出將是d = {'A':0,'A':1} 另外,對於我如何表達我的問題感到抱歉。並不是想讓它看起來像這樣。我現在編輯它。 – garow93

回答

1
In [55]: s = input("Enter a string: ") 
Enter a string: ABC123 

In [56]: d = {char:i for i,char in enumerate(s)} 

In [57]: d 
Out[57]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 0} 

不過請注意,如果有用戶的輸入重複的字符,d將每個字符的最後一次出現的索引:

In [62]: s = input("Enter a string: ") 
Enter a string: ABC123A 

In [63]: d = {char:i for i,char in enumerate(s)} 

In [64]: d 
Out[64]: {'C': 2, '1': 3, '2': 4, '3': 5, 'B': 1, 'A': 6} 
+0

不幸的是,我認爲它需要顯示每個字母的所有實例。所以如果輸入AAA121,它將顯示: d = {'A':0,'A':1,'A':2,'1':3,'2':4,'1':5 } 任何想法?也感謝您的輸入,從來不知道枚舉。 – garow93

+0

這不是字典的工作方式,這意味着您正在爲此任務使用錯誤的數據結構。您可能能夠使用字典的鍵是字符,誰的值是在字符串中找到該字符的位置列表。但是,這仍然不會在你的評論中複製這個例子 – inspectorG4dget

0

呢?

def dict(): 
    user_input = input("Please enter a string") 
    dictionary = {} 
    for i, j in enumerate(user_input): 
     dictionary[j] = i 
    print(dictionary) 
dict("ABC123") 
0

是否確實需要這樣的輸出: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()))) 

除非我錯了,而且更有經驗的人可以插話,你不能讓你想爲你的詞典中的格式「命令」的輸出。

我在移動設備上,所以任何人請隨時糾正的事情。