programing

operator.item getter() 및 sort()는 어떻게 작동합니까?

css3 2023. 9. 27. 18:06

operator.item getter() 및 sort()는 어떻게 작동합니까?

다음 코드가 있습니다.

# initialize
a = []

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])    

# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))    

# print the table
print(a)

4x3 테이블을 만든 다음 연령별로 정렬합니다.제 질문은, 정확히 무엇이key=operator.itemgetter(1)그래요? 그래요?operator.itemgetter함수가 항목의 값을 반환합니까?왜 이렇게 입력하면 안 되는 거지?key=a[x][1]거기? 아님 해도 돼요?오퍼레이터가 어떻게 양식의 특정 값을 다음과 같이 인쇄할 수 있습니까?3x2어느 것이22?

  1. 파이썬은 정확히 어떻게 테이블을 정렬합니까?역순으로 분류해도 됩니까?

  2. 첫 번째 나이와 같은 두 개의 열을 기준으로 분류하고, 그 다음 나이가 같은 b 이름이면 어떻게 분류할 수 있나요?

  3. 제가 어떻게 안하고 할 수 있겠습니까?operator?

당신은 그 모든 것에 대해 약간 혼란스러워 하는 것 같군요.

operator는 일련의 편리한 조작자를 제공하는 내장 모듈입니다.두마디로operator.itemgetter(n)는 반복 가능 객체(예: 목록, 튜플, 집합)를 입력으로 가정하고 n번째 요소를 가져오는 호출 가능을 구성합니다.

그래서 사용할 수 없습니다.key=a[x][1]왜냐하면 파이썬은 무엇이 무엇인지 모르기 때문입니다.x대신에, 당신은 a를 사용할 수 있습니다.lambda함수()elem가변적인 이름일 뿐 마법은 없습니다.):

a.sort(key=lambda elem: elem[1])

아니면 그냥 평범한 기능:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

여기 중요한 사항이 있습니다. python 함수는 1등급 시민이기 때문에 매개 변수로 다른 함수에 전달할 수 있습니다.

기타 질문:

  1. 예, 역순 정렬이 가능합니다. 추가만 하면 됩니다.reverse=True:a.sort(key=..., reverse=True)
  2. 사용할 수 있는 열을 두 개 이상 기준으로 정렬하려면itemgetter다중 지수 포함:operator.itemgetter(1,2), 또는 람다 포함:lambda elem: (elem[1], elem[2]). 이와 같이 표제어는 목록의 각 항목에 대해 신속하게 구성되며, 사전(?) 순서로 서로 비교됩니다(첫 번째 요소 비교, 동일한 경우 - 두 번째 요소 비교 등).
  3. 다음을 사용하여 [3,2]의 값을 가져올 수 있습니다.a[2,1](indices은 0 기반입니다.)연산자 사용 중...이것은 가능하지만 색인화하는 것만큼 깨끗하지는 않습니다.

자세한 내용은 설명서를 참조하십시오.

  1. operator.itemgetter설명된
  2. Python에서 사용자 지정 키로 목록 정렬

Python 초보자를 위한 답

간단히 말하면 다음과 같습니다.

  1. key=의 매개 변수sort는 단일 키 이 아닌 키 함수(소트할 개체에 적용)를 요구합니다.
  2. 그것이 바로 그것입니다.operator.itemgetter(1)제공합니다: 목록과 같은 개체에서 첫 번째 항목을 가져오는 기능입니다.

(정확히는 함수가 아니라 호출 가능한 것이지만, 이는 종종 무시할 수 있는 차이입니다.)

설명서를 읽음으로써 스스로 답할 수 있는 질문을 많이 하고 계시니, 제가 일반적인 조언을 드리겠습니다. 읽어보시고 파이썬 셸에서 실험해보세요.알게 될 겁니다itemgetter호출 가능을 반환합니다.

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

를 .lambda:

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

그리고 그것을 뒤집습니다.

a.sort(key=operator.itemgetter(1), reverse=True)

두 개 이상의 열로 정렬:

a.sort(key=operator.itemgetter(1,2))

방법 정렬을 참조합니다.

#sorting first by age then profession,you can change it in function "fun".
a = []

def fun(v):
    return (v[1],v[2])

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])

a.sort(key=fun)


print a
a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

사용자 정의 함수를 사용하여 배열을 정렬하는 가장 쉬운 방법은 펑툴즈의 cmp_to_key를 사용하는 것입니다.다음은 샘플 코드입니다.

from functools import cmp_to_key

def mine(x,y):
    if(x[1]!=y[1]): return x[1]>y[1]
    else: return x[0]>y[0]
    
a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])  

def mine(a,b):
    if a[1] > b[1]:
        return 1
    elif a[1] < b[1]:
        return -1
    else:
        if a[0] > b[0]:
            return 1
        else:
            return 0
                     
print(sorted(a,key = cmp_to_key(mine)))

언급URL : https://stackoverflow.com/questions/18595686/how-do-operator-itemgetter-and-sort-work