2017-03-31 141 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()))) 

除非我错了,而且更有经验的人可以插话,你不能让你想为你的词典中的格式“命令”的输出。

我在移动设备上,所以任何人请随时纠正的事情。