gpt4 book ai didi

python - Python 的数字字典

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:02 24 4
gpt4 key购买 nike

我是一名非常热爱编程的本科生。我在练习中遇到了一个问题,我不知道如何解决。

问题如下:

给定一个正整数列表,返回一个字典,其中包含数字 1-9 作为键,以该数字开头的数字作为值。注意:并非所有数字都可以使用

示例:

Input: [12, 34, 22, 24, 55, 67, 108, 999] 

Output: {1: [12, 108], 2: [22, 24], 3: [34], 5: [55], 6: [67], 9: [999] }

示例 2:

Input: [10, 20, 30, 40] 

Output: {1: [10], 2: [20], 3: [30], 4: [40]}

我的回答是这样的:

def digit_dictionary(nums):
num = nums.split(',')
list_num = []
for i in range(1,10):
if i == nums[0]:
list.update({i:nums[0]})
return list_num

测试用例是这样的:

Traceback (most recent call last):
File "/grade/run/test.py", line 12, in test_sparse_2
self.assertEqual(digit_dictionary(n), a)
File "/grade/run/bin/digit_dictionary.py", line 2, in digit_dictionary
num = nums.split(',')
AttributeError: 'list' object has no attribute 'split

还有

Traceback (most recent call last):
File "/grade/run/test.py", line 19, in test_sparse
self.assertEqual(digit_dictionary(n), a)
File "/grade/run/bin/digit_dictionary.py", line 2, in digit_dictionary
num = nums.split(',')
AttributeError: 'list' object has no attribute 'split'

还有

Traceback (most recent call last):
File "/grade/run/test.py", line 33, in test_full
self.assertEqual(digit_dictionary(n), a)
File "/grade/run/bin/digit_dictionary.py", line 2, in digit_dictionary
num = nums.split(',')
AttributeError: 'list' object has no attribute 'split'

还有

Traceback (most recent call last):
File "/grade/run/test.py", line 26, in test_empty
self.assertEqual(digit_dictionary(n), a)
File "/grade/run/bin/digit_dictionary.py", line 2, in digit_dictionary
num = nums.split(',')
AttributeError: 'list' object has no attribute 'split'

我已经搜索过 Python 词典,但我仍然感到困惑。谢谢大家的帮助!

最佳答案

您可以对排序列表使用函数 gropby():

from itertools import groupby

l = [12, 34, 22, 24, 55, 67, 108, 999]

f = lambda x: int(str(x)[0])
l = sorted(l, key=f)
{k: list(g) for k, g in groupby(l, key=f)}
# {1: [12, 108], 2: [22, 24], 3: [34], 5: [55], 6: [67], 9: [999]}

关于python - Python 的数字字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54779326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com