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

前端之家收集整理的这篇文章主要介绍了《head first python》——理解数据:列表排序与集合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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]

4、列表的pop操作

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

猜你在找的Python相关文章