4 min read

Python Learning 2学习-序列数据类型

序列是Python中基本的数据结构。序列中的每个元素都分配一个数字,来代表他的位置,或索引,第一索引从0开始,第二个索引是1,以此类推。序列都可以进行的操作包括索引,切片,加,乘,检查等函数。此外,Python也内置确定序列长度以及确定最大和最小的元素方法。以下就为大家介绍最重要的四种序列数据类型:List, Tuple, Dictionary, Set。

列表 List

列表是一种可修改的集合类型,其元素可以是数字、字符串等基本类型,也可以是列表、元组、字典等集合类型,甚至可以是自定义的类型。

创建一个列表,只要用逗号分隔的不同的数据,然后使用方括号括起来即可:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# list2 = list(('a', 'b', 'c'))
print(len(letters))
7

列表元素的读取和更新:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[2:5])
print(letters[10]) # list index out of range error
letters[-2] = 2019
print(letters[-2])
if 'a' in letters:
    print("letter 'a' is in the list")
['c', 'd', 'e']



---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

d:\project\packages\Python\序列数据类型.ipynb Cell 5' in <cell line: 3>()
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000005?line=0'>1</a> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000005?line=1'>2</a> print(letters[2:5])
----> <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000005?line=2'>3</a> print(letters[10]) # list index out of range error
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000005?line=3'>4</a> letters[-2] = 2019
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000005?line=4'>5</a> print(letters[-2])


IndexError: list index out of range

列表的增加和删除:

list = ['apple']
list.insert(1, 'orange')
print(list)
list.remove('apple')
list2 = list.copy()
print(list2)
list = [1, 2, 3, 4, 5]
del list[2]
print(list)
['apple', 'orange']
['orange']
[1, 2, 4, 5]

列表的运算:

list1, list2 = [1, 2, 3], [4, 5, 6]
print(list1 + list2) # [1, 2, 3, 4, 5, 6]
print(list1 * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3] # 相当于将list复制3遍
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]

列表的其他函数:

letters = ['a', 'g', 'f', 'b', 'c', 'd', 'e']
print(sorted(letters))
letters.sort() # The list is sorted permently
print(letters)
letters.reverse()
print(letters)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['g', 'f', 'e', 'd', 'c', 'b', 'a']

元祖 Tuple

Tuple类型和列表类型一样,也是一种序列集合,与列表不同的是,元祖内的数据一旦创建,就不可修改了。元祖的创建很简单,只需要在括号中添加元素,并使用逗号隔开即可:

dimensions = (200, 50) 
dimensions[0] = 250 # error

虽然你不能修改Tuple,但是你可以添加另外赋值

dimensions = (200, 50)
print(dimensions)
dimensions = (400, 10) # works fine
print(dimensions)
(200, 50)
(400, 10)

遍历tuple里面所有的值:

for dimension in dimensions:
    print(dimension)
400
10

元祖中的元素是不允许被删除的,但我们可可以使用del语句来删除整个元祖:

tup = ('Google', 'Facebook', 'Amazon')
del tup
print(tup) # Error

有用的内置函数:

numbers = (5, 9, 11)
print(len(numbers)) # 3
print(min(numbers)) # 5
print(max(numbers)) # 11
3
5
11

字典 Dictionary

字典是一种键值对应的集合,每个关键值都有对应的数据。字典中的每个键值(key => value)都用冒号(:)分割,每对之间用逗号(,)隔开,整个字典包含在花括号中({}),格式如下:

dict = {key1: value1, key2: value2, key3: value3}

字典的键必须是唯一的,但值不必。创建一个简单的字典:

student1 = {'gender': 'male', 'age': 18}
print(student1['gender'])
print(student1['age'])
student1[0] = 'female' # 注意这里不会改变键‘gender’的值,而是创建了一个新的键值
print(student1)
male
18
{'gender': 'male', 'age': 18, 0: 'female'}

添加新的key-value:

student1['grade'] = 250
student1['name'] = 'Enoch'
print(student1)
{'gender': 'male', 'age': 18, 0: 'female', 'grade': 250, 'name': 'Enoch'}

删除字典元素:

del student1['name']
student1.clear()
del student1 # 删除字典

遍历字典:

# Looping through all key-value pairs
user = {
    'username': 'Alex',
    'first': 'dada',
    'last': 'wang',
}

for key, value in user.items():
  print(f"\nKey: {key}")
  print(f"Value: {value}")

# Looping through all the keys in a dictionary
for key in user.keys():
  print(key + ": " + user.get(key))

# Looping through a dictionary's keys in a pariticular order
for key in sorted(user.keys()):
  print(key)

# Looping through all values in a dictionary
for value in user.values():
  print(value.title())

嵌套 Nesting:

# A List in a Dictionary
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
}

print(f"You ordered a {pizza['crust']}-crust pizza"
      "with the following toppings:")

for topping in pizza['toppings']:
  print("\t" + topping)

# A Dictionary in a Dictionary
users = {
    'Enoch': {
        'full_name': 'Xiao Wang',
        'age': 25,
    },
    'Fandy': {
        'full_name': 'Wang Hong',
        'age': 25,
    }
}

for name, information in users.items():
  print(f"{name}: {information['full_name']} is {information['age']} years old.")
You ordered a thick-crust pizzawith the following toppings:
	mushrooms
	extra cheese
Enoch: Xiao Wang is 25 years old.
Fandy: Wang Hong is 25 years old.

集合 Set

集合是一个无序的不重复元素序列。可以使用大括号({})或者set()函数来创建集合,注意:创建一个空集合必须用set()而不是{},因为{}是用来创建一个空字典的。

new_set = {value1, value2, value2, ...}
new_set2 = set(value)
colors = {'red', 'green', 'blue', 'red'}
print(colors)
print('red' in colors)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

d:\project\packages\Python\序列数据类型.ipynb Cell 35' in <cell line: 1>()
----> <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000065?line=0'>1</a> new_set = {value1, value2, value2, ...}
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000065?line=1'>2</a> new_set2 = set(value)
      <a href='vscode-notebook-cell:/d%3A/project/packages/Python/%E5%BA%8F%E5%88%97%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.ipynb#ch0000065?line=2'>3</a> colors = {'red', 'green', 'blue', 'red'}


NameError: name 'value1' is not defined

两个集合之间的运算:

a = set('abcdr')
b = set('aclzm')
print(a - b) # 集合a中包含而集合b中不包含的元素
print(a | b) # 集合a或b中都包含的元素 
print(a & b) # 集合a和b中都包含的元素
print(a ^ b) # 不同时包含于a和b的元素
{'r', 'd', 'b'}
{'b', 'c', 'm', 'r', 'l', 'd', 'a', 'z'}
{'a', 'c'}
{'r', 'z', 'b', 'l', 'd', 'm'}

添加元素可以使用add(x)函数, 将x添加到集合中,如果元素存在,则不进行任何操作:

companies = set(("Google", "Facebook", "Amazon"))
companies.add("Uber")
print(companies)
{'Facebook', 'Google', 'Amazon', 'Uber'}

还有另外一个函数update()也可以用来添加元素,且参数可以是列表、元祖、字典等:

new_set = set(("Google", "Facebook", "Amazon"))
new_set.update({1, 3})
print(new_set)
new_set.update([1, 4], [5, 6])
{1, 3, 'Amazon', 'Facebook', 'Google'}

移除元素有两个函数,一个是remove(x),如果元素x不存在,则会发生错误。另一个是discard()函数,如果元素不存在,不会发生错误:

new_set = set(("Google", "Facebook", "Amazon"))
new_set.remove("Taobao")
new_set.discard("Google")
print(new_set)

Homework

info = {
    'student1': {
        'name': 'Enoch',
        'gender': 'male',
        'age': 18,
        'grade': 12 
    },
    'student2': {
        'name': 'Alice',
        'gender': 'female',
        'age': 17,
        'grade': 11 
    },
    'student3': {
        'name': 'David',
        'gender': 'male',
        'age': 15,
        'grade': 9 
    }
}

info
{'student1': {'name': 'Enoch', 'gender': 'male', 'age': 18, 'grade': 12},
 'student2': {'name': 'Alice', 'gender': 'female', 'age': 17, 'grade': 11},
 'student3': {'name': 'David', 'gender': 'male', 'age': 15, 'grade': 9}}
for key, value in info.items():
    print(f'{key}: name: {value['name']} gender: {value['gender']} age: {value['age']} grade: {value['grade']}') # note:注意单引号和双引号
  Input In [43]
    print(f'{key}: name: {value['name']} gender: {value['gender']} age: {value['age']} grade: {value['grade']}') # note:注意单引号和双引号
                                 ^
SyntaxError: f-string: unmatched '['
for key, value in info.items():
    print(f"{key}: name: {value['name']} gender: {value['gender']} age: {value['age']} grade: {value['grade']}")
    
student1: name: Enoch gender: male age: 18 grade: 12
student2: name: Alice gender: female age: 17 grade: 11
student3: name: David gender: male age: 15 grade: 9
users.items()
for name, information in users.items():
  print(f"{name}: {information['full_name']} is {information['age']} years old.")
Enoch: Xiao Wang is 25 years old.
Fandy: Wang Hong is 25 years old.
info.items()
dict_items([('student1', {'name': 'Enoch', 'gender': 'male', 'age': 18, 'grade': 12}), ('student2', {'name': 'Alice', 'gender': 'female', 'age': 17, 'grade': 11}), ('student3', {'name': 'David', 'gender': 'male', 'age': 15, 'grade': 9})])