(기초) 파이썬 리스트 끼리의 대소비교 질문입니다

조회수 1565회

안녕하세요. 파이썬에서 두 개의 리스트를 비교하는 것을 공부하다가 궁금한 점을 질문드립니다.

num_1=[2,8,3,4,5]
num_2=[4,6,3,1,3]
print(num_1<num_2)

이렇게 코드를 작성하고 실행하였는데, True가 출력되었습니다.

그런데 두 리스트의 인덱스1을 비교하면 num_1>num_2 이므로 False가 나와야 맞는것 아닌가요?

2 답변

  • num_1=[2,8,3,4,5]
    num_2=[4,6,3,1,3]
    
    class comparable_list(list):
        def __lt__(self, other):
            return all(x < y for x, y in zip(self, other))
    
        def __gt__(self, other):
            return all(x > y for x, y in zip(self, other))
    
    n1 = comparable_list(num_1);
    n2 = comparable_list(num_2);
    print(n1 < n2) # False
    
    n3 = comparable_list([9,9,9,9,9]);
    print(n1 < n3) # True
    
    n4 = comparable_list([0,0,0,0,0]);
    print(n1 > n4) # True
    

    le, ge, eq, ne는 생략

  • 리스트의 인덱스1을 비교하면 num_1>num_2 이므로

    ?

    첫번째 엘리먼트를 꺼내서 비교해 보면, num_1[0](=2) < num_2[0](=4) 입니다. 뭔가 착각했나요?

    idle 등에서 리스트 바꾸어 가면서 비교해 보세요. 이해가 갈 겁니다.

    Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> [1] < [0]
    False
    >>> [1] < [2]
    True
    >>> [1] <= [1]
    True
    >>> [1] < [2, 1]
    True
    >>> [1] < [0, 333]
    False
    >>> [1] < ['1']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: '<' not supported between instances of 'int' and 'str'
    >>> ['1'] < ['2']
    True
    >>> [1] < [2, '3']
    True
    >>>              
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)