2016-08-01 62 views
0

我无法看到打印结果的模式。我已经尝试过这种其他的解决方案,但无法得到它的权利=(我怎样才能像原始字符串这样的字典排序?

s = "hi hi hi, how are you? you you" 

print(s) 
s = s.replace('?','') 
s = s.replace('!','') 
s = s.replace(',','') 
s = s.replace('.','') 

l = s.split() 

d = {} 

for i, termo in enumerate(l): 
    if not d.get(termo): 
     d[termo] = [] 
    d[termo].append(i+1) 

print ('d:', d) 

输出示例:

d: {'you': [6, 7, 8], 'how': [4], 'are': [5], 'hi': [1, 2, 3]} 

d: {'are': [5], 'hi': [1, 2, 3], 'how': [4], 'you': [6, 7, 8]} 
+3

词典本质上是无序的。使用'collections.OrderedDict'。 –

+0

你的目标是什么?该输出是预期的输出还是期望的输出? – James

+2

请阅读http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary – cdarke

回答

0

字典是无序集合使用collections.OrderedDict,而不是:

from collections import OrderedDict 

s = "hi hi hi, how are you? you you" 
s = s.translate(None, '?!,.') 
l = s.split() 

d = OrderedDict() 
for i, termo in enumerate(l): 
    d.setdefault(termo, []).append(i) 

print ('d:', d) 

注:

  • collectins.OrderedDict记得添加数据的顺序。随后字典的迭代以相同的顺序发生。

  • str.translate()是从字符串中删除一类字符的一种快速方法。

  • dict.setdefault()如果密钥存在,则返回字典的值,否则返回值。它取代了if x not in d: d[x] = y模式。

+0

罗布,非常感谢你! =)这正是我需要的,我现在明白了! –