words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'}
d = {}
for x in sorted(words):
if x not in d:
d[len(x)]=x
d[len(x)].append(x)
print(d)
AttributeError: 'str' object has no attribute 'append'
该程序的目标是有一个多个键,按字长(即4、5或6个字母)区分,这些键存储按字母顺序排列的值:
{4:'梨','李'5:'苹果','桃'6:'樱桃','橘子','木瓜'}
我在向密钥添加项时遇到问题。我当前得到的输出是(没有附加行):
{4:'李子',5:'桃子',6:'木瓜'}
所以它似乎在删除前面的循环条目。update和append命令返回时出错。你知道吗
您可以使用
collections.defaultdict
创建一个字典,根据每个项的长度存储它们:输出:
此外,
itertools.groupby
可用于较短的解决方案:输出:
不能将
append
转换为字符串;必须从头开始创建dict值list
。您还有两张支票,而不是一张:试试这个:
相关问题 更多 >
编程相关推荐