gpt4 book ai didi

python - 按列表中项目的数字之和对数字列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:41 25 4
gpt4 key购买 nike

我一直在尝试解决一个问题,该问题需要一个返回标题问题的函数。输出的一个示例如下:

sum_of_digits_sorted([56, 2131])

返回

[2131, 56]

2+1+3+1 < 大于 5+6 ,新列表将按照我们在示例中看到的方式进行排序。

我使用了一个在列表上迭代的代码,并且还编写了一种对数字求和的方法,但我不知道如何将它们应用在一起

PD:我是这个网络的新手,所以我不知道如何附加我的程序和那些东西。谢谢!

最佳答案

你可以试试这个:

In [553]: l
Out[553]: [56, 2131]

In [554]: new = [] # define an empty list

In [555]: for c,i in enumerate(l):
...: if c < len(l)-1:
...: lst = map(int, str(l[c])) # converts individual element into a list
...: lst1 = map(int, str(l[c+1]))
...: if sum(lst) > sum(lst1): # sum(lst) gives the sum of the list
...: new.append(l[c+1])
...: new.append(l[c])
...: else:
...: new.append(l[c])
...: new.append(l[c+1])
...:
...:

In [556]: new # will be a sorted list based on the sum of digits of individual elements.
Out[556]: [2131, 56]

关于python - 按列表中项目的数字之和对数字列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53479508/

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