python内置数据结构 - list

简介:

目录: 

  1. 分类

  2. 数字的处理函数

  3. 类型判断

  4. list

  5. 练习题


一. 分类

1). 数值型:int(整型), float(浮点型), complex(复数), bool (布尔型)

2). 序列对象:str (字符串), tuple(元组)  

3). 键值对:set(集合), dict(字典)

二. 数字的处理函数

round(), 对浮点数取近似值

1
2
3
4
5
In [ 1 ]:  round ( 2.675 2 )
Out[ 1 ]:  2.67
 
In [ 2 ]:  round ( 2.676 2 )
Out[ 2 ]:  2.68

在机器中浮点数不一定能精确表达,因为换算成一串1和0后可能是无限位数的,机器已经做出了截断处理。那么在机器中保存的2.675这个数字就比实际数字要小一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。

floor(), 地板, 即总是向小的方向变换.

ceil(), 天花板, 即总是向大的方向变换.

注:floor()和ceil()使用前需先导入math模块. 

1
2
3
4
5
6
7
In [ 3 ]:  import  math
 
In [ 4 ]: math.ceil( 2.675 )
Out[ 4 ]:  3
 
In [ 5 ]: math.floor( 2.675 )
Out[ 5 ]:  2

三. 类型判断

type(obj), 返回类型.

isinstance(obj, class_or_tuple), 返回布尔值.

1
2
3
4
5
6
7
8
9
10
11
12
In [ 1 ]: name  =  'ames'
 
In [ 2 ]:  type (name)
Out[ 2 ]:  str
 
In [ 3 ]:  isinstance (name,  str )
Out[ 3 ]:  True
 
In [ 4 ]:  isinstance (name,  list )
Out[ 4 ]:  False
 
In [ 5 ]:

四. list 

1). 列表的特点 

1
2
3
4
5
6
7
1. 一个队列,一个排列整齐的队伍; 
2. 列表内的个体称作元素,由若干元素组成列表;
3. 元素可以是任意对象(数字,字符串,对象,列表,元组,字典等);
4. 列表内元素有序,可以使用索引; 
5. 线性的数据结构; 
6. 使用[]表示;
7. 列表是可变的;

2). 列表定义, 初始化 

1
2
3
4
5
6
7
In [ 6 ]: lst  =  list ()
 
In [ 7 ]:  type (lst)
Out[ 7 ]:  list
 
In [ 8 ]: lst
Out[ 8 ]: []

3). 列表索引访问 

列表可通过索引访问,索引也称作下标,索引分为正索引和负索引,索引超界会引发 IndexError.

4). 列表 - 增

创建列表 : 

1
In [ 9 ]: fruits_list  =  [ 'apple' 'orange' 'mango' ]

or 

1
In [ 11 ]: fruits_list  =  list ([ 'apple' 'orange' 'mango' ])

增加元素 :   L.append(object)  -> None

1
2
3
4
5
6
7
In [ 12 ]: fruits_list
Out[ 12 ]: [ 'apple' 'orange' 'mango' ]
 
In [ 13 ]: fruits_list.append( 'cherry' )
 
In [ 14 ]: fruits_list
Out[ 14 ]: [ 'apple' 'orange' 'mango' 'cherry' ]

插入元素 :  L.insert(index, object)  -> None

1
2
3
4
In [ 17 ]: fruits_list.insert( 1 'lime' )
 
In [ 18 ]: fruits_list
Out[ 18 ]: [ 'apple' 'lime' 'orange' 'mango' 'cherry' ]

列表扩展 :   L.extend(iterable) -> None

1
2
3
4
5
6
7
8
In [ 22 ]: number  =  [ 'first' 'second' 'third' ]
 
In [ 23 ]: fruits_list.extend(number)
 
In [ 24 ]: fruits_list
Out[ 24 ]: [ 'apple' 'lime' 'orange' 'mango' 'cherry' 'first' 'second' 'third' ]
 
In [ 25 ]:

连接操作 : '+ -'   -> list 

1
2
3
4
5
6
In [ 25 ]: fruits_list  =  [ 'apple' 'lime' 'orange' ]
 
In [ 26 ]: number  =  [ 'first' 'second' 'third' ]
 
In [ 27 ]: fruits_list  +  number
Out[ 27 ]: [ 'apple' 'lime' 'orange' 'first' 'second' 'third' ]

重复操作 :  '*'  -> list 

1
2
3
4
In [ 28 ]: fruits_list  =  [ 'apple' 'lime' 'orange' ]
 
In [ 29 ]: fruits_list  *  2
Out[ 29 ]: [ 'apple' 'lime' 'orange' 'apple' 'lime' 'orange' ]

5). 列表 - 删  

根据value删除元素 :  L.remove(value) -> None  

1
2
3
4
5
6
In [ 33 ]: fruits_list  =  [ 'apple' 'lime' 'orange' 'mango' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 34 ]: fruits_list.remove( 'lime' )
 
In [ 35 ]: fruits_list
Out[ 35 ]: [ 'apple' 'orange' 'mango' 'apple' 'lime' 'orange' 'mango' ]

根据索引值删除元素 :   L.pop([index]) -> item

注:不指定索引值,就从列表尾部弹出一个元素, 索引超界会报错 IndexError

1
2
3
4
5
6
7
8
In [ 36 ]: fruits_list
Out[ 36 ]: [ 'apple' 'orange' 'mango' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 37 ]: fruits_list.pop( 2 )
Out[ 37 ]:  'mango'
 
In [ 38 ]: fruits_list
Out[ 38 ]: [ 'apple' 'orange' 'apple' 'lime' 'orange' 'mango' ]

清除列表所有元素 :  L.clear() -> None 

注:清除列表所有元素后,剩下一个空列表;

1
2
3
4
5
6
7
In [ 39 ]: fruits_list
Out[ 39 ]: [ 'apple' 'orange' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 40 ]: fruits_list.clear()
 
In [ 41 ]: fruits_list
Out[ 41 ]: []

6). 列表 - 改 

通过索引访问修改 :  list[index] = value 

注:索引不要越界. 

1
2
3
4
5
6
In [ 44 ]: fruits_list  =  [ 'apple' 'lime' 'orange' ]
 
In [ 45 ]: fruits_list[ 1 =  'mango'
 
In [ 46 ]: fruits_list
Out[ 46 ]: [ 'apple' 'mango' 'orange' ]

7). 列表 - 查

查找元素对应的索引值 :  L.index(value, [start, [stop]]) -> integer 

注:查找时,匹配到一个就立即返回,否则报错 ValueError   

1
2
3
4
In [ 48 ]: fruits_list  =  [ 'apple' 'orange' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 49 ]: fruits_list.index( 'apple' 1 5 )
Out[ 49 ]:  2

匹配列表中元素出现次数 :  L.count(value) -> integer  

1
2
3
4
In [ 50 ]: fruits_list  =  [ 'apple' 'orange' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 51 ]: fruits_list.count( 'apple' )
Out[ 51 ]:  2

8). 列表其他操作: 

将列表元素反转 :   L.reverse() -> None 

1
2
3
4
5
6
7
In [ 52 ]: fruits_list
Out[ 52 ]: [ 'apple' 'orange' 'apple' 'lime' 'orange' 'mango' ]
 
In [ 53 ]: fruits_list.reverse()
 
In [ 54 ]: fruits_list
Out[ 54 ]: [ 'mango' 'orange' 'lime' 'apple' 'orange' 'apple' ]

对列表排序 :  L.sort(key=None, reverse=False) -> None

注:排序时默认升序,reverse为True,则反转降序排列;key指定一个函数,指定如何排序。 

1
2
3
4
5
6
7
8
9
10
11
12
In [ 59 ]: fruits_list
Out[ 59 ]: [ 'mango' 'orange' 'lime' 'apple' 'orange' 'apple' ]
 
In [ 60 ]: fruits_list.sort()
 
In [ 61 ]: fruits_list
Out[ 61 ]: [ 'apple' 'apple' 'lime' 'mango' 'orange' 'orange' ]
 
In [ 62 ]: fruits_list.sort(key = len )
 
In [ 63 ]: fruits_list
Out[ 63 ]: [ 'lime' 'apple' 'apple' 'mango' 'orange' 'orange' ]

判断一个元素是否在列表中 :  in  

注:返回结果为bool.

1
2
In [ 64 ]:  'apple'  in  fruits_list
Out[ 64 ]:  True

9). 列表复制  

列表复制 :  L.copy() -> list -- a shallow copy of L 

shadow copy : 影子拷贝,也叫浅拷贝,遇到引用类型,只是复制了一个引用而已. 

深拷贝 :  copy模块提供了 deepcopy

浅拷贝在内存中只额外创建第一层数据.

深拷贝在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

浅拷贝:  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
In [ 65 ]: lst0  =  [ 1 2 , [ 3 4 5 ],  6 ]
 
In [ 66 ]: lst1  =  lst0.copy()
 
In [ 67 ]: lst0  = =  lst1
Out[ 67 ]:  True
 
In [ 68 ]: lst1[ 2 ][ 2 =  10
 
In [ 69 ]: lst1
Out[ 69 ]: [ 1 2 , [ 3 4 10 ],  6 ]
 
In [ 70 ]: lst1  = =  lst0
Out[ 70 ]:  True

深拷贝: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [ 71 ]:  import  copy
 
In [ 72 ]: lst2  =  [ 1 2 , [ 3 4 5 ],  6 ]
 
In [ 73 ]: lst3  =  copy.deepcopy(lst2)
 
In [ 74 ]: lst2  = =  lst3
Out[ 74 ]:  True
 
In [ 75 ]: lst3[ 2 ][ 2 =  10
 
In [ 76 ]: lst3
Out[ 76 ]: [ 1 2 , [ 3 4 10 ],  6 ]
 
In [ 77 ]: lst2  = =  lst3
Out[ 77 ]:  False

10). 随机数  

使用random模块 

randint(a, b)返回[a, b]之间的整数;

choice(seq) 从非空序列的元素中随机挑选一个元素;

randrange([start], stop, [, step]) 从指定范围内按指定基数递增的集合中获取一个随机数,基数缺省值为1. 

random.shuffle(list) -> None  就地打乱列表元素.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
In [ 78 ]:  import  random
 
In [ 79 ]: random.randint( 1 10 )
Out[ 79 ]:  3
 
In [ 80 ]: random.choice( range ( 10 ))
Out[ 80 ]:  9
 
In [ 81 ]: random.randrange( 1 10 2 )
Out[ 81 ]:  9
 
In [ 82 ]: lis  =  list ( range ( 10 ))
 
In [ 83 ]: lis
Out[ 83 ]: [ 0 1 2 3 4 5 6 7 8 9 ]
 
In [ 84 ]: random.shuffle(lis)
 
In [ 85 ]: lis
Out[ 85 ]: [ 6 5 3 1 7 4 9 0 8 2 ]
 
In [ 86 ]:

五. 练习题

1. 求100以内的素数.

方法1:  合数一定可以分解为几个质数的乘积.  

1
2
3
4
5
6
7
8
lis  =  []
for  in  range ( 2 100 ):
     for  in  lis:
         if  %  = =  0 :
             break
     else :
         lis.append(i)
print (lis)

方法2: 合数就是能被从2开始到自己的平方根的正整数整除的数.

1
2
3
4
5
6
7
8
9
import  math
lis  =  []
for  in  range ( 2 100 ):
     for  in  range ( 2 , math.ceil(math.sqrt(i))):
         if  %  = =  0 :
             break
     else :
         lis.append(i)
print (lis)

方法3: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import  math
lis  =  []
flag  =  False
for  in  range ( 2 100 ):
     for  in  lis:
         if  %  = =  0 :
             flag  =  True
             break
         elif  j > =  math.ceil(math.sqrt(i)):
             flag  =  False
             break
     if  not  flag:
         lis.append(i)
print (lis)

2. 计算杨辉三角前六行. 

201709241506244053755533.png

方法1:下一行依赖上一行所有元素,是上一行所有元素的两两相加的和,再在两头各加1.

1
2
3
4
5
6
7
8
9
triangle  =  [[ 1 ], [ 1 1 ]]
=  6
for  in  range ( 2 , n):
     cur  =  [ 1 ]
     for  in  range (i - 1 ):
         cur.append(triangle[ - 1 ][j]  +  triangle[ - 1 ][j + 1 ])
     cur.append( 1 )
     triangle.append(cur)
print (triangle)

方法2:方法1的变体. 

1
2
3
4
5
6
7
8
9
10
triangle  =  []
for  in  range ( 6 ):
     row  =  [ 1 ]
     triangle.append(row)
     if  = =  0 :
         continue
     for  in  range (i - 1 ):   
         row.append(triangle[i - 1 ][j]  +  triangle[i - 1 ][j + 1 ])
     row.append( 1 )
print (triangle)

方法3 - while 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
=  6
oldline  =  []
newline  =  [ 1 ]
length  =  0
print (newline)
for  in  range ( 1 , n):
     oldline  =  newline.copy()
     oldline.append( 0 )   # 尾部加0, 相当于两端加0.
     newline.clear()
     offset  =  0
     while  offset < =  i:
         newline.append(oldline[offset - 1 +  oldline[offset])
         offset  + =  1
     print (newline)

方法3 - for  

1
2
3
4
5
6
7
8
9
10
11
12
13
=  6
oldline  =  []
newline  =  [ 1 ]
length  =  0
print (newline)
for  in  range ( 1 , n):
     oldline  =  newline.copy()
     oldline.append( 0 )
     newline.clear()
     offset  =  0
     for  in  range (i + 1 ):
         newline.append(oldline[j - 1 +  oldline[j])
     print (newline)


本文转自 羽丰1995 51CTO博客,原文链接:http://blog.51cto.com/13683137989/1968207
相关文章
|
4月前
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
576 0
|
4月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
227 4
|
5月前
|
存储 消息中间件 NoSQL
【Redis】常用数据结构之List篇:从常用命令到典型使用场景
本文将系统探讨 Redis List 的核心特性、完整命令体系、底层存储实现以及典型实践场景,为读者构建从理论到应用的完整认知框架,助力开发者在实际业务中高效运用这一数据结构解决问题。
|
7月前
|
存储 监控 安全
企业上网监控系统中红黑树数据结构的 Python 算法实现与应用研究
企业上网监控系统需高效处理海量数据,传统数据结构存在性能瓶颈。红黑树通过自平衡机制,确保查找、插入、删除操作的时间复杂度稳定在 O(log n),适用于网络记录存储、设备信息维护及安全事件排序等场景。本文分析红黑树的理论基础、应用场景及 Python 实现,并探讨其在企业监控系统中的实践价值,提升系统性能与稳定性。
304 1
|
10月前
|
索引 Python
Python错误 - 'list' object is not callable 的问题定位与解决
出现编程问题并不可怕,关键在于是否可以从中学习与成长。遇到'list' object is not callable这样的错误,我们不仅需要学会应对,更需要了解其背后的原因,避免类似的问题再次出现。记住,Python的强大功能和灵活性同时也意味着我们需要对其理解更准确,才能更好的使用它。
1248 70
|
存储 开发者 索引
Python 中常见的数据结构
这些数据结构各有特点和适用场景,在不同的编程任务中发挥着重要作用。开发者需要根据具体需求选择合适的数据结构,以提高程序的效率和性能
538 156
|
存储 算法 搜索推荐
Python 中数据结构和算法的关系
数据结构是算法的载体,算法是对数据结构的操作和运用。它们共同构成了计算机程序的核心,对于提高程序的质量和性能具有至关重要的作用
497 153
|
存储 缓存 监控
局域网屏幕监控系统中的Python数据结构与算法实现
局域网屏幕监控系统用于实时捕获和监控局域网内多台设备的屏幕内容。本文介绍了一种基于Python双端队列(Deque)实现的滑动窗口数据缓存机制,以处理连续的屏幕帧数据流。通过固定长度的窗口,高效增删数据,确保低延迟显示和存储。该算法适用于数据压缩、异常检测等场景,保证系统在高负载下稳定运行。 本文转载自:https://www.vipshare.com
377 66

热门文章

最新文章

推荐镜像

更多