[英]How to sort a list based on the summation of second elements of tuple within a list?
我關心的是我的一個變量,它在列表中有如下元組。
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
我正在嘗試獲取列表的第二個元組元素的總和,例如[3,2,5]
並根據該總和對它們進行排序。 所以該求和的結果應該是。
result1 = [(['a','b','c'],[10]),(['d','e','f'],[12]),(['g','h','j'],[7])]
那么我預期的最終結果應該按降序排序。
result = [['d','e','f'],['a','b','c'],['g','h','j']]
一個優雅的班輪:
result = [a for a, b in sorted(test, key = lambda x : sum(x[1]), reverse=True)]
sorted
使用傳遞的 iterable 返回一個排序列表,在本例中為test
key
定義排序的基礎。 這是一個 lambda 表達式,它接受元組x
並返回元組sum(x[1])
第二部分的總和
reverse
設置為降序排序
最后我們使用列表理解來擺脫數字部分b
並只保留字母a
我認為一步一步可能會有所幫助,因為你提到你是新手。
>>> a = [(e[0], sum(e[1])) for e in test]
>>> a
[(['a', 'b', 'c'], 10), (['d', 'e', 'f'], 12), (['g', 'h', 'j'], 7)]
>>> b=sorted(a, key=lambda e:-e[-1])
>>> b
[(['d', 'e', 'f'], 12), (['a', 'b', 'c'], 10), (['g', 'h', 'j'], 7)]
>>> c=[e[0] for e in b]
>>> c
[['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'j']]
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
for i in range(len(test)):
test[i]=list(test[i])
test[i][1]=sum(test[i][1]) #this iteration helps to sum up the elements
print(test)
new_list=[]
maxi=0
for i in test:
if i[1]<maxi:
new_list= new_list+[i[0]]
else:
new_list=[i[0]]+ new_list #this is to sort in descending order
maxi=i[1]
print(new_list)
output:
[[['a', 'b', 'c'], 10], [['d', 'e', 'f'], 12], [['g', 'h', 'j'], 7]]
[['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'j']]
>>>
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
def sum_of_list(l):
# Returns sum of the list
total = 0
for val in l:
total = total + val
return total
def Sort_Tuple(tup):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
tup.sort(key = lambda x: x[1], reverse = True)
return tup
result1 = []
for t in test:
result1.append((t[0],sum_of_list(t[1])))
result1 = Sort_Tuple(res1)
result = [ _[0] for _ in result1]
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.