python——列表操作符

 1. 比较操作符

  >>> list1 = [123]
  >>> list2 = [456]
  >>> list1 > list2
    False

   列表中有单个元素时,直接比较相对应的元素大小即可,如果列表中有多个元素呢?如下:

  >>> list1 = [123,456]
  >>> list2 = [456,123]
  >>> list1 > list2
    False

 列表中有多个元素时,首先从列表中的第0个位置的元素相比较大小,如果哪个列表的第0个位置的元素大,就认为该列表大。如果相等的话就一直比较下去,直到有一项大,就认为该列表大。

 2. 逻辑操作符

 (1)>>> list3 = [123,456]
     >>> (list1 < list2) and (list1 == list3)
       True
 (2)>>> list4 = list1 + list2
        >>> list4
       [123, 456, 456, 123]       

     操作符“+”用于连接列表,不能连接不同的种类,如(3)所示,“+”左边为列表,右边为字符串,出现错误。

 (3)>>> list1 + "小明"
    Traceback (most recent call last):
    File "<pyshell#11>", line 1, in <module>
    list1 + "小明"
    TypeError: can only concatenate list (not "str") to list
 3.  连接操作符

         >>> list1 * 3
    [123, 456, 123, 456, 123, 456]

      操作符“*”用于重复列表中的元素。

猜你喜欢

转载自www.cnblogs.com/carlber/p/9379646.html