列表和元组
列表
列表和元组都是一个可以放置任意数据类型的有序集合。这里需要注意三个词,任意、有序、集合。其实就是说明列表和元组是可以放置任意数据类型,其次是有序的,另外,它是一个集合。
在python中列表的典型特征就是[],中括号中间用逗号‘,’进行分割。
l = [1,2,3]
print(type(l))
<class 'list'>
列表中可以存放任意的数据类型,如下:列表中放置有整数、字符串、列表、元组、集合、字典。
l=[1,2,'name',[1,2],(1,),{2,3,1},{'name':'tank','age':20}]
print(type(l))
<class 'list'>
列表中存放的数据是有序的。在python中列表的索引是从0开始的,可以根据索引来获取列表中的元素,如下所示:
l=[1,2,'name',[1,2],(1,),{2,3,1},{'name':'tank','age':20}]
print(l[0])#获取的是第一个元素
print(l[1])#第二个元素
print(l[2])
print(l[4])
print(l[-1])#最后一个元素
1
2
name
(1,)
{'name': 'tank', 'age': 20}
切片操作,可以获取列表中的部分元素。需要注意,切片操作的左包含规则,意思就是右边的数字不包含,列如:
l=[1,2,'name',[1,2],(1,),{2,3,1},{'name':'tank','age':20}]
print(l[0:3])#获取索引是0、1、2的元素组成的列表,不包好索引为3的元素
print(l[0:])#获取全部元素,并重新组成一个列表
print(l[-2:])#获取最后两个元素,并重新组成一个列表
[1, 2, 'name']
[1, 2, 'name', [1, 2], (1,), {1, 2, 3}, {'name': 'tank', 'age': 20}]
[{1, 2, 3}, {'name': 'tank', 'age': 20}]
这里需要注意,切片操作获取的是由元素组成的列表,而不是单纯的元素。
列表的拼接,比如:两个列表的拼接,
a=['hello']
b=['world']
print(a + b)#两个列表中的元素合并,组成一个新的列表
print(3 * a)#复制3个a列表,组成一个新的列表
['hello', 'world']
['hello', 'hello', 'hello']
判断一个元素是否在列表当中,用in,比如:
l=[1,2,'name',[1,2],(1,),{2,3,1},{'name':'tank','age':20}]
print('name' in l)
print('hello' in l)
True
False
列表常用方法
append方法:列表末尾附加一个元素
a=['hello']
print(a)
a.append('world')
print(a)
help(a.append)#help方法,可以查看append用法
['hello']
['hello', 'world']
Help on built-in function append:
append(object, /) method of builtins.list instance
Append object to the end of the list.
extend方法:列表末尾添加多个元素,注意extend中的参数是一个可迭代的对象
a=['hello']
b=['world']
help(a.extend)
print(a)
a.extend('world')
print(a)
a.extend(b)
print(a)
Help on built-in function extend:
extend(iterable, /) method of builtins.list instance
Extend list by appending elements from the iterable.
['hello']
['hello', 'w', 'o', 'r', 'l', 'd']
['hello', 'w', 'o', 'r', 'l', 'd', 'world']
index方法:获取列表中某元素的第一次出现的索引位置
l=[1,2,1,'name',[1,2],(1,),{2,3,1},'name',{'name':'tank','age':20}]
print(l.index('name'))#获取‘name’元素第一次出现的索引
print(l.index('name',4))#从索引4开始,获取‘name’元素第一次出现的索引
help(l.index)
3
7
Help on built-in function index:
index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
Return first index of value.
Raises ValueError if the value is not present.
count方法:查询某个元素出现的次数
l=[1,2,1,'name',[1,2],(1,),{2,3,1},'name',{'name':'tank','age':20}]
print(l.count('name'))
print(l.count(2))
help(l.count)
2
1
Help on built-in function count:
count(value, /) method of builtins.list instance
Return number of occurrences of value.
pop方法:从列表中移除指定位置的元素,并返回
l=[1,2,1,'name',[1,2],(1,),{2,3,1},'name',{'name':'tank','age':20}]
print(l.pop(1))#删除索引为1的元素
print(l)
2
[1, 1, 'name', [1, 2], (1,), {1, 2, 3}, 'name', {'name': 'tank', 'age': 20}]
insert方法:在指定索引位置插入元素
l=[1,2,1,'name',[1,2],(1,),{2,3,1},'name',{'name':'tank','age':20}]
help(l.insert)
print(l.insert(1,'hello'))#在索引为1的地方,插入元素
print(l)
Help on built-in function insert:
insert(index, object, /) method of builtins.list instance
Insert object before index.
None
[1, 'hello', 2, 1, 'name', [1, 2], (1,), {1, 2, 3}, 'name', {'name': 'tank', 'age': 20}]
clear方法:清除列表中的元素
l=[1,2,1,'name',[1,2],(1,),{2,3,1},'name',{'name':'tank','age':20}]
help(l.clear)
print(l.clear())
print(l)
Help on built-in function clear:
clear() method of builtins.list instance
Remove all items from list.
None
[]
查找列表的内建函数
help(list)
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Stable sort *IN PLACE*.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
元组
再次复习一遍,列表和元组都是一个可以放置任意数据类型的有序集合。这里需要注意三个词,任意、有序、集合。其实就是说明列表和元组是可以放置任意数据类型,其次是有序的,另外,它是一个集合。
在python中元组的典型特征就是(),中括号中间用逗号‘,’进行分割。
t1=(1)#这是一个int类型,注意括号内,没有逗号,有逗号就是元组类型
t2=(1,)
t3=()
t4=(1,'name',2,(1,2),{1,2,3})#元组内可以放置任意数据类型
print(type(t1))
print(type(t2))
print(type(t3))
print(type(t4))
<class 'int'>
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
元组和列表非常相似,但是需要注意的是元组内的数据不能被修改,相当于只读的列表,例如:
t=(1,'name',2,(1,2),{1,2,3})
print(t[1])
t[1]='hello'
name
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-60f400e2cef9> in <module>
1 t=(1,'name',2,(1,2),{1,2,3})
2 print(t[1])
----> 3 t[1]='hello'
TypeError: 'tuple' object does not support item assignment
元组中存放的数据是有序的。在python中元组的索引是从0开始的,可以根据索引来获取元组中的元素,如下所示:
t=(1,'name',2,(1,2),{1,2,3})
print(t[0])
print(t[1])
print(t[2])
1
name
2
切片操作,可以获取元组中的部分元素,这和列表一样,需要注意,切片操作的左包含规则,意思就是右边的数字不包含,列如:
t=(1,'name',2,(1,2),{1,2,3})
print(t[:])#获取全部元组中的数据,并组成新的元组
print(t[0:3])#获取索引从0到2的数据,并组成新的元组
print(t[-2:])#获取倒数2个数据,并组成新的元组
(1, 'name', 2, (1, 2), {1, 2, 3})
(1, 'name', 2)
((1, 2), {1, 2, 3})
元组的内建函数
help(tuple)
Help on class tuple in module builtins:
class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.