Comparing lists in Python

后端 未结 3 1478
猫巷女王i
猫巷女王i 2020-12-21 10:20

Say I have list1 = [1,2,3,4] and list2 = [5,6,7,8]. How would I compare the first element, 1, in list1 with the first el

3条回答
  •  猫巷女王i
    2020-12-21 10:53

    The default comparison operators compare lists in lexicographical order. So you can say things like:

    >>> [1, 2, 3, 4] < [5, 6, 7, 8]
    True
    

    If instead you want to compute the elementwise comparison, you can use map and cmp (or any other operator:

    >>> map(cmp, [1, 2, 3, 4], [5, 6, 7, 8])
    [-1, -1, -1, -1]
    

提交回复
热议问题