您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

《head first python》——理解数据:列表排序与集合

5b51 2022/1/14 8:25:24 python 字数 3177 阅读 843 来源 www.jb51.cc/python

1、sort()与sorted()——数据排序 sort()对数据原地排序,sorted()创建原地副本。用法是:

概述

1、sort()与sorted()——数据排序

sort() 对数据原地排序,sorted()创建原地副本。用法是:

obj.sort();

obj2 = sorted(obj1)

>> a = [2,7,5,1,9]
>>> b = sort(a)
Traceback (most recent call last):
  File "
  
   ",line 1,in 
   
    
    b = sort(a)
NameError: name 'sort' is not defined
>>> a
    .sort()
>>> print a
[1,2,9]
   
  
>> a = [2,9]
>>> b = a.sorted()
Traceback (most recent call last):
  File "
  
   ",in 
   
    
    b = a
    .sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> b = sorted(a)
>>> print a
[2,9]
>>> print b
[1,9]
   
  

 通过传递reverse = True,可以对sort()和sorted()传参,逆序排列。注意True首字母大写。

>> a = [2,9]
>>> b = sorted(a,reverse = True)
>>> a,b
([2,9],[9,1])
>>> a.sort(reverse = True)
>>> a
[9,1]

2.python集合数据项——删除重复项

python提供了集合数据结构,显著特点是:数据无序,且不允许重复。用set()可创建一个新集合。

sorted(集合) 可以返回一个列表对象。

>> m = [1,1]
>>> m
[1,1]
>>> m = {1,3,1}
>>> m
set([1,3])
>>> s=set([8,8])
>>> s
set([8,2])
>>> sorted(s)
[1,8]

3.创建新列表的方式——new_list = [ func for item in old_list ]

<code class="language-python">>>> a = [2,9]

b = [i/2 for i in a]
b
[1,4]

b = [i/2 for i in a]
b
[1,4]

b = [i/2 for i in a]
b
[1,4]

4、列表的pop操作

>> a= [2,4,1]
a.pop(0)
2
a
[3,1]

总结

以上是编程之家为你收集整理的《head first python》——理解数据:列表排序与集合全部内容,希望文章能够帮你解决《head first python》——理解数据:列表排序与集合所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶