Python列表处理

(1)list 列表操作包含以下函数。
       

  • 比较两个列表的函数, 以前的版本有cmp方法, 3. 之后取消了,但是可以直接用“>”,“<”, 或者“=”, 来直接比较,这种方法对于字符串也是适用的
  • len(list):列表元素个数,也适用于元组,字符串
  • max(list):列表元素的最大值, 也适用于元组,字符串
  • min(list):列表元素的最小值, 也适用于元组,字符串
  • list(seq): 将元组转换成列表。


   (2) liest列表操作方法。


  • list.append(obj):在列表末尾添加新的对象
  • list.count(obj):统计某个元素在列表中出现的次数
  • list.extend(seq):在列表末尾一次追加另一个序列中的多个值(用新列表扩展原来的列表)
  • liest.index(obj):从列表中找出某个值第一个匹配项的索引位置
  • list.insert(index,obj):将对象插入列表的指定位置
  • list.pop(obj=list[-1]):移除列表中的一个元素(默认是最后一个元素),不过也可以指定
  • list.remove(obj):移除列表中的某个值的第一个匹配项
  • list.reverse():反向列表中的元素
  • list.sort(key = None, reverse = False): 对列表进行排序,reverse参数有False和True决定排序是由小到大还是由大到小,https://docs.python.org/3.3/howto/sorting.html 
      

            Key Functions

           Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

      For example, here’s a case-insensitive string comparison:

>>>
     >>>  sorted( "This is a test string from Andrew" .split(), key = str .lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
          

A common pattern is to sort complex objects using some of the object’s indices as keys. For example:

>>>
>>> student_tuples  = [     ('john', 'A', 15),     ('jane', 'B', 12),     ('dave', 'B', 10), ] >>>  sorted(student_tuples, key = lambda student: student[ 2])    # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值