第三章Python列表、元组、字典
第三章Python列表、元组、字典
本节所讲内容:
1.3.1 Python变量赋值
1.3.2 python列表
1.3.3 python元组
1.3.4 python 字典
1.3.1 Python变量赋值
常量 不变化的量,比如 数字、字符串都是
变量 存储常量,通常由变量名指出
赋值 就是将一个常量指向一个变量
Name = “while”
Python 是一门弱变量的语言,所用变量即用即生成,变量的类型随着值的类型的修改而修改
命名可用内容
字母
数字
下划线
1、 数字不可以开头,也不可以纯数字
2、 __开头代表私有
3、 __name__ 代表魔术方法
4、 关键字不可以用于命名
import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
5、 命名要具有具体意义,禁止无意义的命名,比如 a,b1,bb
常见的命名
名词
name = 1
动宾结构
get_page = 1
getPage = 1
GetPage = 1
变量赋值的三种方式
传统赋值
name = “while”
链式赋值
name = user = “while”
序列解包赋值
name,age = “whlie”,10
>>> name = "while"
>>> name
'while'
>>> name = user = "while"
>>> name
'while'
>>> user
'while'
>>> name,age = "while",18
>>> name
'while'
>>> age
18
>>>
变量不存在
>>> hello
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
hello
NameError: name 'hello' is not defined
变量和常量不对应
name,age = "while",18,1
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
name,age = "while",18,1
ValueError: too many values to unpack (expected 2)
1.3.2 python列表
列表是一个元素以逗号分割,以中括号包围的,有序的,可修改的序列。
Python 2
1、 list
2、 []
3、 range
4、 xrange
Python 3
1、 list
>>> list("abcde")
['a', 'b', 'c', 'd', 'e']
>>> str(['a', 'b', 'c', 'd', 'e'])
"['a', 'b', 'c', 'd', 'e']"
>>> "".join(['a', 'b', 'c', 'd', 'e'])
'abcde'
>>>
2、 []
>>> [1,"a",[1,2]]
[1, 'a', [1, 2]]
3、 range
>>> range(100)
range(0, 100)
>>> list(range(100))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
列表的索引
列表的索引和字符串的索引类似,但不完全相同,因为列表可以修改,所以我们可以通过列表的索引来修改列表。
一样的部分
>>> [1,2,3]
[1, 2, 3]
>>> ourlist = [1,2,3,4,5]
>>> ourlist
[1, 2, 3, 4, 5]
>>> ourlist[1]
2
>>> ourlist[-1]
5
>>> ourlist[:]
[1, 2, 3, 4, 5]
>>> ourlist[::2]
[1, 3, 5]
>>> ourlist[::-1]
[5, 4, 3, 2, 1]
不一样的部分
ourlist[1] = "s"
>>> ourlist
[1, 's', 3, 4, 5]
>>> [1,2,3][1] = "s"
>>> [1,2,3]
[1, 2, 3]
索引超出序列范围
ourlist[5]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
ourlist[5]
IndexError: list index out of range
列表的方法
|
列表的添加 |
append |
追加,在列表的尾部加入指定的元素 |
|
extend |
将指定序列的元素依次追加到列表的尾部 |
|
|
insert |
将指定的元素插入到对应的索引位上,注意负索引 |
|
|
列表的删除 |
pop |
弹出,返回并删除指定索引位上的数据,默认-1 |
|
remove |
从左往右删除一个指定的元素 |
|
|
del |
删除是python内置功能,不是列表独有的 |
|
|
列表的查找 注 列表没有find方法 |
count |
计数,返回要计数的元素在列表当中的个数 |
|
index |
查找,从左往右返回查找到的第一个指定元素的索引,如果没有找到,报错 |
|
|
列表的排序 |
reverse |
索引顺序倒序 |
|
sort |
按照ascii码表顺序进行排序 |
Append
ourList = [1,"a",2,3,5]
>>> ourList.append("c")
>>> ourList
[1, 'a', 2, 3, 5, 'c']
>>> ourList.append([1,2,3])
>>> ourList
[1, 'a', 2, 3, 5, 'c', [1, 2, 3]]
Extend
ourList = [1,"a",2,3,5]
>>> ourList.extend("123")
>>> ourList
[1, 'a', 2, 3, 5, '1', '2', '3']
Insert
ourList = [1,"a",2,3,5]
>>> ourList.insert("c",2)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
ourList.insert("c",2)
TypeError: 'str' object cannot be interpreted as an integer
>>> ourList.insert(2,"c")
>>> ourList
[1, 'a', 'c', 2, 3, 5]
Pop
ourList = [1,"a",2,3,5]
>>> ourList.pop
<built-in method pop of list object at 0x02F2FC38>
>>> ourList.pop()
5
>>> ourList
[1, 'a', 2, 3]
>>> ourList.pop()
3
>>> ourList
[1, 'a', 2]
>>> ourList.pop(1)
'a'
>>> ourList
[1, 2]
>>>
Remove
ourList = [1,"a",2,3,5]
>>> ourList.remove(1)
>>> ourList
['a', 2, 3, 5]
>>> ourList = [1,"a",2,3,5,1]
>>> ourList.remove(1)
>>> ourList
['a', 2, 3, 5, 1]
Del
>>> ourList = [1,"a",2,3,5,1]
>>> del ourList[1]
>>> ourList
[1, 2, 3, 5, 1]
>>> del ourList
>>> ourList
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
ourList
NameError: name 'ourList' is not defined
Count
>>> ourList = [1,"a",2,3,5,1]
>>> ourList.count(1)
2
Index
>>> ourList.index(2)
2
>>> ourList.index("x")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
ourList.index("x")
ValueError: 'x' is not in list
Reverse
ourList = [1,"a",2,3,5,1]
>>> ourList.reverse()
>>> ourList
[1, 5, 3, 2, 'a', 1]
Sort
ourList = [1,"a",2,3,5,1]
>>> ourList.sort()
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
ourList.sort()
TypeError: unorderable types: str() < int()
>>> ourList = [1,2,3,5,1]
>>> ourList.sort()
>>> ourList
[1, 1, 2, 3, 5]
1.3.3 python元组
元组是元素以逗号分割,以小括号包围的有序的,不可修改的序列。
tuple()
( 1,2,3,”a”)
>>> tuple("hello")
('h', 'e', 'l', 'l', 'o')
>>> ("a",1,"2")
('a', 1, '2')
>>>
元组的索引:
元组的索引和字符串完全一致
ourTuple =
tuple("hello")
>>> ourTuple
('h', 'e', 'l', 'l', 'o')
>>> ourTuple[1]
'e'
>>> ourTuple[-1]
'o'
>>> ourTuple[1:3]
('e', 'l')
>>> ourTuple[1:3:2]
('e',)
>>> ourTuple[3:1:-1]
('l', 'l')
元组的特性
元组可以不加括号
>>> 1,2
(1, 2)
单元素元组需要加逗号
>>> type([1])
<class 'list'>
>>> type((1))
<class 'int'>
>>> type((1,))
<class 'tuple'>
元组不可修改,所以我们在配置文件当中多看到元组
Django 配置的一部分
DATABASE = (
Os.path.join(BASEDIR,”TEMPLATE”),
)
元组的方法
|
元组的查找 |
index |
从左往右返回第一个遇到的指定元素的索引,如果没有,报错 |
|
count |
返回元组当中指定元素的个数 |
>>> a = (1,2,3,4,2,2,4)
>>> a.count(2)
3
>>> a.count(4)
2
>>> a.index(4)
3
>>>
元组和字符串的区别
1、 元组和字符串都是有序的,不可修改的序列
2、 元组的元素可以是任何类型,字符串的元素只能是字符
3、 元组的元素长度可以任意,字符串的元素长度只能为1
1.3.4 python 字典
字典一个元素呈键值对的形式,以逗号分割,以大括号包围的无序的,可以修改的序列。
字典是python基础数据类型当中唯一一个映射关系的数据类型通常对应JSON
{}
>>> ourDict = {"a":1,"b":2}
>>> ourDict
{'b': 2, 'a': 1}
>>>
Fromkeys
>>> ourDict = {}.fromkeys("abcde")
>>> ourDict
{'b': None, 'a': None, 'd': None, 'e': None, 'c': None}
>>> ourDict = {}.fromkeys("abcde","hello")
>>> ourDict
{'b': 'hello', 'a': 'hello', 'd': 'hello', 'e': 'hello', 'c': 'hello'}
>>>
Dict
Zip函数:将几个序列对应索引位上的元素分到一个元组当中,总的形成一个列表,子元组的个数取决于提供的序列最小长度.
Python2直接返回对象
Python3返回对象的内存地址,需要用列表进行转换
Zip = zip("abcdefg","12345")
>>> Zip
<zip object at 0x02F8A738>
>>> list(Zip)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), ('e', '5')]
>>> Zip = zip("abcdefg","12345","abcdefg","12345",)
>>> list(Zip)
[('a', '1', 'a', '1'), ('b', '2', 'b', '2'), ('c', '3', 'c', '3'), ('d', '4', 'd', '4'), ('e', '5', 'e', '5')]
>>>
Dict
>>> dict([("a",1),("c",2)])
{'a': 1, 'c': 2}
dict(zip("abcdefg","12345"))
{'e': '5', 'b': '2', 'd': '4', 'a': '1', 'c': '3'}
>>>
ourzip = zip("abcdefg","12345")
>>> ourdict = dict(ourzip)
>>> ourdict
{'e': '5', 'b': '2', 'd': '4', 'a': '1', 'c': '3'}
字典的特点:
因为字典是无序的,所以字典没有索引值,
因为字典没有索引值,所以字典以键取值,(字典的键相当于列表的索引)
>>> ourzip = zip("abcdefg","12345")
>>> ourdict = dict(ourzip)
>>> ourdict
{'e': '5', 'a': '1', 'd': '4', 'c': '3', 'b': '2'}
>>> ourdict["e"]
'5'
>>>
因为字典以键取值,所以字典的键唯一且不可修改,
因为字典的键不可修改,所以列表和字典不可以给字典做键。
nextdict = {"a":1,1:"a",(1,2):"c"}
>>> nextdict
{(1, 2): 'c', 1: 'a', 'a': 1}
>>> nextdict = {"a":1,1:"a",(1,2):"c",{"a":1}:1}
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
nextdict = {"a":1,1:"a",(1,2):"c",{"a":1}:1}
TypeError: unhashable type: 'dict'
>>>
字典的方法
|
字典的取值 |
keys |
获取字典所有的键 |
|
values |
获取字典所有的值 |
|
|
get |
以键取值,如果指定键不存在,默认返回None,可以指定返回内容 |
|
|
update |
更新指定键的内容,如果键不存在,创建 |
|
|
setdefault |
设置默认,如果键存在,返回值,如果键不存在,创造键,值默认为None,值也可以自定义 |
|
|
items |
返回字典键值呈元组形式的格式 |
|
|
字典的删除 |
pop |
弹出,返回并删除指定键对应的值 |
|
popitem |
随机弹出一个键值元组,这里随机的原因是因为字典无序 |
|
|
clear |
清空字典 |
字典的取值
ourdict = {"a":1,"b":2,"c":3}
>>> ourdict.keys()
dict_keys(['a', 'b', 'c'])
>>> ourdict.values()
dict_values([1, 2, 3])
>>> list(ourdict.keys())
['a', 'b', 'c']
>>> list(ourdict.values())
[1, 2, 3]
>>> ourdict.get("a")
1
>>> ourdict["a"]
1
>>> ourdict.get("x")
>>> ourdict["x"]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
ourdict["x"]
KeyError: 'x'
>>> ourdict.update({"a":1})
>>> ourdict
{'a': 1, 'b': 2, 'c': 3}
>>> ourdict.update({"a":2})
>>> ourdict
{'a': 2, 'b': 2, 'c': 3}
>>> ourdict.update({"x":2})
>>> ourdict
{'a': 2, 'b': 2, 'c': 3, 'x': 2}
>>> ourdict+{"y":4}
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
ourdict+{"y":4}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> ourdict
{'a': 2, 'b': 2, 'c': 3, 'x': 2}
>>> ourdict.setdefault("a")
2
>>> ourdict.setdefault("y")
>>> ourdict
{'a': 2, 'b': 2, 'c': 3, 'x': 2, 'y': None}
>>> ourdict.setdefault("h",6)
6
>>> ourdict
{'a': 2, 'h': 6, 'x': 2, 'b': 2, 'c': 3, 'y': None}
>>> dict([(1,2)])
{1: 2}
>>> ourdict.items()
dict_items([('a', 2), ('h', 6), ('x', 2), ('b', 2), ('c', 3), ('y', None)])
>>> list(ourdict.items())
[('a', 2), ('h', 6), ('x', 2), ('b', 2), ('c', 3), ('y', None)]
字典的删除
ourdict = {'a': 2, 'h': 6, 'x': 2, 'b': 2, 'c': 3, 'y': None}
>>> ourdict
{'b': 2, 'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2}
>>> ourdict.pop()
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
ourdict.pop()
TypeError: pop expected at least 1 arguments, got 0
>>> ourdict.pop("b")
2
>>> ourdict
{'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2}
>>> ourdict.popitem()
('h', 6)
>>> ourdict.popitem()
('a', 2)
>>> ourdict.popitem()
('c', 3)
>>> ourdict = {'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2}
>>> ourdict.items()
dict_items([('c', 3), ('y', None), ('x', 2), ('h', 6), ('a', 2)])
>>> ourdict.popitem()
('c', 3)
>>> ourdict.popitem()
('y', None)
>>> ourdict.popitem()
('x', 2)
>>> ourdict.popitem()
('h', 6)
>>> ourdict.popitem()
('a', 2)
>>> ourdict
{}
>>> ourdict = {'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2}
>>> ourdict
{'c': 3, 'y': None, 'x': 2, 'h': 6, 'a': 2}
>>> ourdict.clear()
>>> ourdict
{}
Python 2
Has_key
Python 3
In
ourdict = {'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2}
>>> "h" in ourdict
True
>>> 6 in ourdict
False
字典的拷贝属于浅层拷贝,拷贝和被拷贝对象的嵌套层同属一个内存,一个修改另一个也会修改
>>> ourdict = {'h': 6, 'a': 2, 'c': 3, 'y': None, 'x': 2,"z":[1]}
>>> ourdict_1 = ourdict.copy()
>>> ourdict
{'h': 6, 'a': 2, 'x': 2, 'z': [1], 'y': None, 'c': 3}
>>> ourdict_1 = ourdict.copy()
>>> ourdict_1
{'h': 6, 'a': 2, 'x': 2, 'z': [1], 'y': None, 'c': 3}
>>> ourdict["h"] = 7
>>> ourdict
{'h': 7, 'a': 2, 'x': 2, 'z': [1], 'y': None, 'c': 3}
>>> ourdict_1
{'h': 6, 'a': 2, 'x': 2, 'z': [1], 'y': None, 'c': 3}
>>> ourdict["z"][0] = 3
>>> ourdict
{'h': 7, 'a': 2, 'x': 2, 'z': [3], 'y': None, 'c': 3}
>>> ourdict_1
{'h': 6, 'a': 2, 'x': 2, 'z': [3], 'y': None, 'c': 3}
数据类型的总结
|
|
str |
list |
tuple |
dict |
|
是否有序 |
是 |
是 |
是 |
否 |
|
是否可修改 |
不 |
可 |
不 |
可 |
|
方法多少 |
很多 |
一般 |
很少 |
较多 映射关系 |