Python字典向键添加不同的值?
我想做一个函数,它遍历一个列表,并生成一个字典,其中包含列表中每个事物的键,以及在键后面的列表中一个事物的值Python字典向键添加不同的值?,python,dictionary,Python,Dictionary,我想做一个函数,它遍历一个列表,并生成一个字典,其中包含列表中每个事物的键,以及在键后面的列表中一个事物的值 def function(s : str) -> {str:{str}}: listt=list(s) dictt= {} for i in listt[:-1]: if i not in dictt: dictt[i] = set() dictt[i].update(listt[listt.index
def function(s : str) -> {str:{str}}:
listt=list(s)
dictt= {}
for i in listt[:-1]:
if i not in dictt:
dictt[i] = set()
dictt[i].update(listt[listt.index(i)+1])
return dictt
print(function('bookeeper'))
应返回:
{'b': {'o'}, 'k': {'e'}, 'p': {'e'}, 'o': {'o', 'k'}, 'e': {'e', 'p', 'r'}}
但实际上返回:
{'b': {'o'}, 'k': {'e'}, 'p': {'e'}, 'o': {'o'}, 'e': {'e'}}
不要使用list.index()
;只匹配字母的第一次出现;对于'o'
,它永远找不到第二个'o'
;您只能重复向集合中添加相同的字符
用于向循环中添加索引,而不是:
def function(s : str) -> {str:{str}}:
listt=list(s)
dictt= {}
for next_index, char in enumerate(listt[:-1], 1):
if char not in dictt:
dictt[char] = set()
dictt[char].update(listt[next_index])
return dictt
我从1开始执行enumerate()
,而不是默认的0,因此它始终表示下一个位置
演示:
现在,它正在工作,让我们把它简化一点;例如,用于在缺少密钥时将集合添加到字典中。字符串已经是序列,也无需将其强制转换为列表:
def function(s : str) -> {str:{str}}:
dictt = {}
for next_index, char in enumerate(s[:-1], 1):
dictt.setdefault(char, set()).update(s[next_index])
return dictt
除了使用enumerate()
,我们还可以使用zip()
将单词的字母配对:
def function(s : str) -> {str:{str}}:
dictt = {}
for char, next_char in zip(s, s[1:]):
dictt.setdefault(char, set()).update(next_char)
return dictt
您的问题是
index()
总是返回字符串中的第一个索引,因此您将反复向集合中添加相同的字符
试试像这样的东西
def function(s : str) -> {str:{str}}:
dictt = {}
for pos, char in enumerate(s[:-1]):
if char not in dictt:
dictt[char] = set()
dictt[char].update(s[pos+1])
return dictt
下面是另一个答案:
def func(string):
arr = set(string)
res = {}
for char in arr:
index = [i for i in range(len(string)) if string[i] == char]
temp = []
for i in index:
if i == len(string) - 1:
continue
temp.append(string[i + 1])
if temp:
res[char] = temp
return res
func('bookeeper')
>>> {'b': ['o'], 'e': ['e', 'p', 'r'], 'k': ['e'], 'o': ['o', 'k'], 'p': ['e']}
我记得几分钟前看到这个问题:grate:)你能帮我一下吗…你用的是哪一个python版本?@user1153551:python3,很明显。函数注释给出了它。@sshashank124:请参见,以及,这将生成列表,而不是集合。例如,它会为
top
产生错误的结果(在o
之后两次p
),而且效率极低;您的算法使用O(N^2)时间;单词中每增加一个字符,所用时间就会增加一倍。
def func(string):
arr = set(string)
res = {}
for char in arr:
index = [i for i in range(len(string)) if string[i] == char]
temp = []
for i in index:
if i == len(string) - 1:
continue
temp.append(string[i + 1])
if temp:
res[char] = temp
return res
func('bookeeper')
>>> {'b': ['o'], 'e': ['e', 'p', 'r'], 'k': ['e'], 'o': ['o', 'k'], 'p': ['e']}