我需要我的字典关键字格式为'/ cat/‘,但我总是得到多个正斜杠。下面是我的代码:
# Defining the Digraph method #
def digraphs(s):
dictionary = {}
count = 0;
while count <= len(s):
string = s[count:count + 2]
count += 1
dictionary[string] = s.count(string)
for entry in dictionary:
dictionary['/' + entry + '/'] = dictionary[entry]
del dictionary[entry]
print(dictionary)
#--End of the Digraph Method---#下面是我的输出:
我这样做:
有向图(‘我的猫在帽子里’)
{'///in///': 1, '/// t///': 1, '/// c///': 1, '//s //': 1, '/my/': 1, '/n /': 1, '/e /': 1, '/ h/': 1, '////ha////': 1, '//////': 21, '/is/': 1, '///ca///': 1, '/he/': 1, '//th//': 1, '/t/': 3, '//at//': 2, '/t /': 1, '////y ////': 1, '/// i///': 2}发布于 2012-08-30 10:54:27
在Python中,通常不应该在修改对象时遍历对象。不要修改你的字典,而是创建一个新的字典:
new_dict = {}
for entry in dictionary:
new_dict['/' + entry + '/'] = dictionary[entry]
return new_dict或者更简洁(Python 2.7及更高版本):
return {'/' + key + '/': val for key, val in dictionary.items()}一个更好的方法是从一开始就跳过创建原始字典:
# Defining the Digraph method #
def digraphs(s):
dictionary = {}
for count in range(len(s)):
string = s[count:count + 2]
dictionary['/' + string + '/'] = s.count(string)
return dictionary
#--End of the Digraph Method---#发布于 2012-08-30 10:51:05
当循环遍历字典时,您会向字典中添加条目,因此您的新条目也会包含在循环中,并且会再次添加额外的斜杠。一种更好的方法是制作一个包含您想要的新关键字的新字典:
newDict = dict(('/' + key + '/', val) for key, val in oldDict.iteritems())正如@Blender指出的,如果你使用的是Python 3,你也可以使用字典理解:
{'/'+key+'/': val for key, val in oldDict.items()}https://stackoverflow.com/questions/12189184
复制相似问题