最近开始写监控项目代码,需要使用到python 因为之前一直用的是java 很久没有用python了,很多语法都忘记了。今天正好趁着周末时间来学习下python的重点语法: 列表、元组和字典
序列是python中最基本的数据结构,序列中的每个元素都分配一个数字,对应的是元素的位置,或者叫索引。第一个索引是0,第二个索引是1
python有6个序列的内置类型,最常见的是列表和元组。序列都可以进行操作的操作包括索引、切片、加、乘、检查成员。Python已经内置确定序列的长度以及确定最大和最小元素的方法。
列表是python最常用的数据类型,可以作为一个方括号内的逗号分隔值出现。列表的数据项不需要具有相同的数据类型。
创建一个列表,只需要把逗号分隔的不同的数据项使用方括号括起来即可。
我们来看看实例:
list1 = ['A',1,3.14,'Google']
print(list1)
我们看下运行结果:
['A', 1, 3.14, 'Google']
与字符串的索引一样,列表索引从0开始,列表可以进行截取、组合等。
我们再看个实例,访问列表中的值: 使用下标(索引)来访问列表中的值,也可以使用方括号的形式截取字符。
list1 = ['A',1,3.14,'Google']
list2 =['Google',99,'123',9.123,1.8]
print('list1列表的第2个元素',list1[1])
print('print2列表的第4个元素',list2[3])
我们来看下运行结果:
list1列表的第2个元素 1
print2列表的第4个元素 9.123
下面我们看下怎么更新列表中的数据: 可以直接使用修改或更新索引对应的值,还有一种就是使用 append()方法来添加列表项,我们来看看实例
list1 = ['A',1,3.14,'Google']
list2 =['Google',99,'123',9.123,1.8]
print('list1列表的第2个元素',list1[1])
print('print2列表的第4个元素',list2[3])
list1[1] = 500list2[3] = 'Hello'print('list1列表的第2个元素',list1[1])
print('print2列表的第4个元素',list2[3])
修改和更新索引对应的值,运行结果为:
list1列表的第2个元素 1
print2列表的第4个元素 9.123
list1列表的第2个元素 500
print2列表的第4个元素 Hello
然后我们使用 append()方法试下:
list1 = ['A',1,3.14,'Google']
list2 =['Google',99,'123',9.123,1.8]
print('list1列表的第2个元素',list1[1])
print('print2列表的第4个元素',list2[3])
list1[1] = 500list2[3] = 'Hello'print('list1列表的第2个元素',list1[1])
print('print2列表的第4个元素',list2[3])
list1.append(1)
print(list1)
看下执行结果:
['A', 500, 3.14, 'Google', 1]
相当于在最后添加了一个元素.如果我们想指定列表索引修改为指定的值可以吗?我们来试试
list2.append(2,'cool')
print(list2)
运行下看看结果:
Traceback (most recent call last):
File "/Users/lg/PycharmProjects/pythonProject/main.py", line 28, in <module>
list2.append(2,'cool')
TypeError: append() takes exactly one argument (2 given)