lists can be modified but strings can not be modified. For example,
>>> My_idle_name = 'Lebron James'
>>> My_idle_name
'Lebron James'
>>> Name_list = list(My_idle_name)
>>> Name_list
['L', 'e', 'b', 'r', 'o', 'n', ' ', 'J', 'a', 'm', 'e', 's']
>>> My_idle_name[0]='C'
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
My_idle_name[0]='C'
TypeError: 'str' object does not support item assignment
>>> Name_list[0]='C'
>>> Name_list
['C', 'e', 'b', 'r', 'o', 'n', ' ', 'J', 'a', 'm', 'e', 's']
元组和列表一样,它是有序的,可以包含多种数据类型,用()来表示。作为一个序列,元组也可以使用序列的操作,比如slice (:), * 等等,但是,元组中的元素不能改变。例如:
>>> MyTuple = ('a', 1, [1,2], True)
>>> MyTuple
('a', 1, [1, 2], True)
>>> MyTuple[0]='b'
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
MyTuple[0]='b'
TypeError: 'tuple' object does not support item assignment
>>> MyTuple*2
('a', 1, [1, 2], True, 'a', 1, [1, 2], True)
>>> MyTuple[0:-1]
('a', 1, [1, 2])
集合是无序的,用{ } 来表示。因为集合是无序的,所以不能用index 来索引。集合不能被看成是一个数列,但是它仍然支持一些运算,如下表所示:
例子如下:
>>> MySet = {'a', 1, False}
>>> MySet
{False, 1, 'a'}
>>> MySet[1]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
MySet[1]
TypeError: 'set' object does not support indexing
>>> len(MySet)
3
>>> 'a' in MySet
True
>>> MySet2 = {1,'b',True}
>>> MySet|MySet2
{False, 1, 'b', 'a'}
>>> MySet
{False, 1, 'a'}
>>> MySet2
{1, 'b'}
>>> MySet2 = {1,2,3,'Kyrie Irving'}
>>> MySet|MySet2
{False, 1, 2, 3, 'a', 'Kyrie Irving'}
>>> MySet
{False, 1, 'a'}
>>> MySet2
{1, 2, 3, 'Kyrie Irving'}
>>> MySet&MySet2
{1}
>>> MySet-MySet2
{False, 'a'}
>>> MySet<=MySet2
False
>>>
集合本身也有自己的运算,子交并补是数学中最常见的集合运算。
代码如下:Note: 下面代码为https://runestone.academy/runestone/static/pythonds/Introduction/GettingStartedwithData.html#tab-setmethods
中的代码
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>> yourSet = {99,3,100}
>>> mySet.union(yourSet)
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet | yourSet
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet.intersection(yourSet)
{3}
>>> mySet & yourSet
{3}
>>> mySet.difference(yourSet)
{False, 4.5, 6, 'cat'}
>>> mySet - yourSet
{False, 4.5, 6, 'cat'}
>>> {3,100}.issubset(yourSet)
True
>>> {3,100}<=yourSet
True
>>> mySet.add("house")
>>> mySet
{False, 4.5, 3, 6, 'house', 'cat'}
>>> mySet.remove(4.5)
>>> mySet
{False, 3, 6, 'house', 'cat'}
>>> mySet.pop()
False
>>> mySet
{3, 6, 'house', 'cat'}
>>> mySet.clear()
>>> mySet
set()
>>>
字典有键和键值key-value.
teams = {'Cleveland':'Cavaliers','Houston':'Rockets'}
teams['Golden States']='Warriors'
teams
{'Cleveland': 'Cavaliers', 'Houston': 'Rockets', 'Golden States': 'Warriors'}
teams['Cleveland']
'Cavaliers'
for i in teams:
print('The team of ', i, ' is ', teams[i])
The team of Cleveland is Cavaliers
The team of Houston is Rockets
The team of Golden States is Warriors