Can I do the followign problem using Dict comprehensions
Given this list: a_list= [ 22, 55, 77, 234, 765, 1234] Produce a code snippet that produces this output: a_dict = {2:[22, 55 77], 3:[234, 765], 4:[1234]} The keys in the dictionary are the length of the digits in a_list.
My solution:
tmp_list = []
key = len(str(i))
if key in a_dict:
tmp_list = a_dict[key]
tmp_list.append(i)
a_dict[key] = tmp_list
else:
tmp_list.append(i)
a_dict[key] = tmp_list ```
CodePudding user response:
Using groupby, sort and then group by length:
a_list = [22, 55, 77, 234, 765, 1234]
print({k: list(map(int, g)) for k, g in groupby(sorted(map(str, a_list), key=lambda el: len(str(el))), key=len)})
Output:
{2: [22, 55, 77], 3: [234, 765], 4: [1234]}
CodePudding user response:
It ain't pretty, but it works.
{
key: [i[key] for i in [{len(str(num)): num} for num in a_list] if key in i]
for key in [len(str(num)) for num in a_list]
}
>>> {2: [22, 55, 77], 3: [234, 765], 4: [1234]}
Be warned, this approach is not readable or efficient in terms of looping.
CodePudding user response:
Using collections.defaultdict
is going to be more efficient than a comprehension in this case. Also, math.log10
is more efficient than len(str(digit))
:
res = defaultdict(list)
for digit in digits:
res[int(log10(digit)) 1].append(digit)
{2: [22, 55, 77], 3: [234, 765], 4: [1234]}