是否确实需要这样的输出: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