source

두 번째 매개 변수를 기준으로 튜플 정렬

ittop 2023. 9. 9. 10:15
반응형

두 번째 매개 변수를 기준으로 튜플 정렬

다음과 같은 모양의 튜플 목록이 있습니다.

("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)

제가 원하는 것은 튜플의 두번째 값에 따라 오름차순으로 정렬된 목록입니다.그래서 L[0]은("Person 2", 8)분류한 후에

이거 어떻게 해요?도움이 된다면 Python 3.2.2 사용하기.

사용할 수 있습니다.key에 매개 변수를 지정합니다.list.sort():

my_list.sort(key=lambda x: x[1])

아니면, 조금 더 빨리,

my_list.sort(key=operator.itemgetter(1))

(다른 모듈과 마찬가지로 다음과 같은 작업이 필요합니다.import operator사용할 수 있도록 하는 것입니다.)

적용할 수도 있습니다.sorted목록에 function이 있습니다. 그러면 새 정렬된 목록이 반환됩니다.이것은 Sven Marnach가 위에서 제시한 답변에 추가된 것일 뿐입니다.

# using *sort method*
mylist.sort(key=lambda x: x[1]) 

# using *sorted function*
l = sorted(mylist, key=lambda x: x[1]) 
    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> 로그 원

언급URL : https://stackoverflow.com/questions/8459231/sort-tuples-based-on-second-parameter

반응형