【发布时间】:2021-10-21 03:06:06
【问题描述】:
我正在尝试对列表进行排序。排序基于在每个单独的列表中添加数字。所以我有一个看起来像这样的列表:
[['Turkey', '27', '73'], ['United States', '705', '1850'], ['Brazil', '26', '46'], ['Mexico', '35', '65'], ['Singapore', '17', '6']]
我需要根据将 27 和 73 与 705 添加到 1850 等相比较来对该列表进行排序。正如您在上面看到的,该列表几乎是排序的,因为它看起来像这样:
[['Brazil', '26', '46'], ['Mexico', '35', '65'], ['Singapore', '17', '6'], ['United States', '705', '1850'], ['Turkey', '27', '73']]
我拥有的冒泡排序代码如下所示:
def sort_graph_data(self, graph_data):
for i in range(len(graph_data)):
current_value_sum_first = self.get_list_total(graph_data[i])
for j in range(len(graph_data) - 1):
current_value_sum_second = self.get_list_total(graph_data[j + 1])
if current_value_sum_first < current_value_sum_second:
graph_data[j + 1], graph_data[j] = graph_data[j], graph_data[j + 1]
print(graph_data)
def get_list_total(self, value):
current_value_sum = 0
for v in value[1:]:
v = int(v)
current_value_sum = v + current_value_sum
return current_value_sum
我有方法get_list_total 的原因是因为每个数字都属于<class 'numpy.str_'> 类。这可以解决,但与对列表进行排序相比,我并不担心它。
我还要说每个单独的列表可能比两个数字长:
['United States', '705', '1850', '45', '12']
所以解决方案必须考虑到这个因素。我想过用 lambda 函数和sort 做点什么,但没有运气。
我所拥有的几乎可以工作,但正如你所看到的那样不完全。
【问题讨论】:
标签: python python-3.x list sorting