Python—迭代整个列表并将其分配给dict
我试图用python构建一个程序,它遍历字符串列表并将它们分配给dict,其中键是该字符串中的字符数,值是单词本身Python—迭代整个列表并将其分配给dict,python,Python,我试图用python构建一个程序,它遍历字符串列表并将它们分配给dict,其中键是该字符串中的字符数,值是单词本身 (例如:2:be,到3:foo,bar)。然而,我的程序只执行并分配一些给定的字符串列表。我能做些什么来让它工作呢?我想这很简单: text = "This is a test for my program" new_dict = {} text_list = text.split() word_tester = 2 for word in text_list: word
(例如:2:be,到3:foo,bar)。然而,我的程序只执行并分配一些给定的字符串列表。我能做些什么来让它工作呢?我想这很简单:
text = "This is a test for my program"
new_dict = {}
text_list = text.split()
word_tester = 2
for word in text_list:
word_tester = len(word)
if len(word) == word_tester:
new_dict[word_tester] = word
return new_dict
#1
text = "This is a test for my program"
final_dct = {len(word):word for word in text.split() if len(word)==len(word_tester)}
#2
text = "This is a test for my program"
new_dict = {}
text_list = text.split()
for word in text_list:
if len(word) in new_dict and word not in new_dict[len(word)]:
new_dict[len(word)].append(word)
else:
new_dict[len(word)] = [word]
return new_dict
请注意,在本词典中,键4被分配给test,而不是this,因为每个键只能分配一个值。在这种情况下,要使该值成为列表,可以使用:
for word in text_list:
new_dict[len(word)] = word
我想你只需要确保在空间上分开。我运行了这个,它运行正常
for word in text_list:
if len(word) in new_dict:
new_dict[len(word)].append(word)
else:
new_dict[len(word)] = [word]
问题是一个键只能有一个值,所以每次有一个给定长度的单词时都会覆盖它。要解决这个问题,可以将字符串列表存储为字典值,而不是像另一个示例中建议的那样存储单个字符串
collections
模块中的一个方便工具是defaultdict
,它允许您在键没有值时定义默认条目。一个常见的用例是使用defaultdict(list)
以空列表开始键入。这样您就不必检查密钥是否不存在,也不必手动将其初始化为空列表。将此合并到您的示例中,您将得到:
text = "This is a test for my program"
text_list = text.split(" ")
new_dict = {}
for word in text_list:
if len(word) in new_dict and word not in new_dict[len(word)]:
new_dict[len(word)].append(word)
else:
new_dict[len(word)] = [word]
#print(new_dict)
#{1: ['a'], 2: ['is', 'my'], 3: ['for'], 4: ['This', 'test'], 7: ['program']}
return new_dict
字典只能为每个键保存一个值,但这个值本身可以是一个列表。我不认为有
word\u tester
以及内部if
有什么意义。也许您忽略了当前只处理长度为2的单词这一事实?代码中的一个问题是,您的word\u tester=len(word)
后面紧跟着if len(word)==word\u tester
。在这种情况下,len(word)
将始终等于word\u tester
,因为您刚刚在前一行中使它们相等!您可能需要使用另一个变量来跟踪字长。这将只保留最后出现的字长。所以新的dict会有my和skip,is,对吧。。。我正在努力。。。不清楚OP期望什么,但我假设其中有一个列表case@Mokshyam好的,现在应该修好了。我不认为你需要检查这个词是否在新词中,但实际上你的想法比我强,使用set
而不是list
和add
而不是append
将允许您在不进行该检查的情况下处理该问题。如果您不关心存储重复项,则可以使用set
仅存储唯一的单词:将defaultdict(list)
替换为defaultdict(set)
和新单词[len(word)]。用新单词[len(word)]追加(word)
。添加(word)
。您可以使用同一字符串多次调用add
,集中只存储一个实例。
from collections import defaultdict
text = "This is a test for my program"
new_dict = defaultdict(list) # a dictionary whose default value is an empty list
text_list = text.split()
for word in text_list:
# append this word to the list of words with the same length
new_dict[len(word)].append(word)
return new_dict