python 3 一些常用的内置数据结构介绍

本文详细介绍了 Python 中的列表、元组、集合、字典等数据结构的基本操作及高级应用,如列表推导式、集合推导式和字典推导式的使用方法,以及如何利用这些数据结构解决实际问题。

一、列  表


     1、在Python中列表是可以改变的,而字符串和元组不能。
      2、下面是列表的应用:
    • 使用append() 方法和pop() 方法便可以将列表作为堆栈来使用。(先进后出)
    • 使用 list 模拟队列通过,引入库deque和popleft ( ) 来实现。

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()   #The first to arrive now leaves
'Eric'
>>> queue.popleft() #The second to arrive now leaves
'John'
>>> queue       # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

二、列  表  推  导  式 


  • 列表推导式提供了从序列创建列表的便捷方法,将一些操作应用于某个序列的每个元素,获得的结果为新生成的元素。如果希望表达式推导出一个元组,就必须使用括号。

demo如下:
1、首先 将列表中每个数值乘三,获得一个新的列表 :
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]

2、在例如 : 
>>> [[x, x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

3、对序列里每一个元素逐个调用某方法( 去掉前后的空格 ):
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']

4、用 if 子句作为过滤器:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[ ]

5、循环和其它技巧
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]

6、使用复杂表达式或嵌套函数   round 函数功能是四舍五入
>>> [str(round(355/113, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']


  • 嵌套列表解析(嵌套的列表)

demo实例:将一个数组转置 - - - >下面三种方法思想类似:
原矩阵:
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

法一:   理解为两重循环 。
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

法二:  
>>> transposed = [ ]
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

法三:
>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

  • del 语句:它可以从一个列表中依索引删除一个元素,这与pop( )函数不同。此外,可以用 del 语句从列表中删除一个切割,或清空整个列表 。

demo 如下:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

也可以用 del 删除实体变量:
>>> del a

三 、元  祖  和  序  列


     元组由若干逗号分隔的值组成 , 元祖是可以嵌套的,元组在输出时总是有括号的,以便于正确表达嵌套结构。在输入时可能有或没有括号, 不过通常括号都会加上 。

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))


四 、集  合


     集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素可以用大括号({})创建集合。注意:如果要创建一个空集合,你必须用 set( ) 而不是 { } ;而 { } 创建一个空的字典,    

集合也支持推导式:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

五 、字  典


     序列是以连续的整数为索引,而字典以关键字为索引,关键字可以是任意不可变类型,通常用字符串或数值。它是无序的键=>值对集合,同一个字典内关键字必须是互不相同。用一对大括号创建一个空的字典:{ }

demo例子:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

以下是几种创建字典的方法:

构造函数 dict() 直接从键值对元组列表中构建字典:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

字典推导可以用来创建词典:
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

如果关键字只是简单的字符串,可以使用如下关键字参数指定键值对创建字典:
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

遍历的一些小方法:

  • 在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来 。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...    print(k, v)
...

gallahad the pure
robin the brave

  • 在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到 。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...    print(i, v)
...

0 tic
1 tac
2 toe

  • 同时遍历两个或更多的序列,可以使用 zip() 组合:

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...    print('What is your {0}?  It is {1}.'.format(q, a))
...

What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

  • 要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数 :

>>> for i in reversed(range(1, 10, 2)):
...    print(i)
...

  • 要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...    print(f)
...

apple
banana
orange
pear


注:此python教程,来自菜鸟教程,学习后,自己的学习笔记,以备以后遗忘时,在方便回顾学习。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smilejiasmile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值