字典
字典是将键(key)映射到值(value)的无序数据结构。值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组。
# Defining a dictionary
webstersDict = {'person': 'a human being, whether an adult or child', 'marathon': 'a running race that is about 26 miles', 'resist': ' to remain strong against the force or effect of (something)', 'run': 'to move with haste; act quickly'}
webstersDict
{'person': 'a human being, whether an adult or child',
'marathon': 'a running race that is about 26 miles',
'resist': ' to remain strong against the force or effect of (something)',
'run': 'to move with haste; act quickly'}
访问字典中的值
# Finding out the meaning of the word marathon
# dictionary[key]
webstersDict['marathon']
'a running race that is about 26 miles'
更新字典
# add one new key value pair to dictionary
webstersDict['shoe'] = 'an external covering for the human foot'
# return the value for the 'shoe' key
webstersDict['shoe']
'an external covering for the human foot'
# update method, update or add more than key value pair at a time
webstersDict.update({'shirt': 'a long- or short-sleeved garment for the upper part of the body'
, 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'})
webstersDict
{'marathon': 'a running race that is about 26 miles',
'person': 'a human being, whether an adult or child',
'resist': ' to remain strong against the force or effect of (something)',
'run': 'to move with haste; act quickly',
'shirt': 'a long- or short-sleeved garment for the upper part of the body',
'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'}
# Removing key from dictionary
del webstersDict['resist']
webstersDict
{'marathon': 'a running race that is about 26 miles',
'person': 'a human being, whether an adult or child',
'run': 'to move with haste; act quickly',
'shirt': 'a long- or short-sleeved garment for the upper part of the body',
'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'}
使用get()方法返回给定键的值(在字数统计任务中很有价值)
# incorporate into get example and such below.
storyCount = {'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
storyCount
{'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
# if key doesnt exist,
# specify default value for keys that dont exist.
# returns value for key you enter if it is in dictionary
# else it returns the value you have for default
storyCount.get('Michael', 0)
12
# When you dont set default value for key that doesnt exist,
# it defaults to none
print(storyCount.get('run'))
None
# Making default value for key that doesn't exist 0.
print(storyCount.get('run', 0))
0
删除键,但同时可以返回值
count = storyCount.pop('the')
print(count)
90
遍历字典
# return keys in dictionary
print(storyCount.keys())
# return values in dictionary
print(storyCount.values())
['is', 'runs', 'Michael']
[100, 5, 12]
# iterate through keys
for key in storyCount:
print(key)
is
Michael
runs
# iterate through keys and values
for key, value in webstersDict.items():
print('key', 'value')
person a human being, whether an adult or child
marathon a running race that is about 26 miles
resist to remain strong against the force or effect of (something)
run to move with haste; act quickly
元组
元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。 元组使用括号,而列表使用方括号。
初始化一个元组
1、可以通过让()没有值来初始化空元组
# Way 1
emptyTuple = ()
2、还可以使用元组函数初始化空元组。
# Way 2
emptyTuple = tuple()
可以通过用逗号分隔值的序列来初始化具有值的元组。
# way 1
z = (3, 7, 4, 2)
# way 2 (tuples can also can be created without parenthesis)
z = 3, 7, 4, 2
重要的是要记住,如果要创建仅包含一个值的元组,则需要在项目后面添加一个逗号。
# tuple with one value
tup1 = ('Michael',)
# tuple with one value
tup2 = 'Michael',
# This is a string, NOT a tuple.
notTuple = ('Michael')
访问元组内的值
元组中的每个值都有一个指定的索引值。值得注意的是,python是一种基于零索引的语言。所有这些意味着元组中的第一个值是索引0。
# Initialize a tuple
z = (3, 7, 4, 2)
# Access the first item of a tuple at index 0
print(z[0])
3
Python还支持负索引。负索引从元组结束开始。使用负索引来获取元组中的最后一项有时会更方便,因为您不必知道元组的长度来访问最后一项。
# print last item in the tuple
print(z[-1])
2
切分元组
切分操作返回包含所请求项的新元组。切分很适合在元组中获取值的子集。对于下面的示例代码,它将返回一个元组,其中包含索引0的对象,而不包括索引2的对象。
# Initialize a tuple
z = (3, 7, 4, 2)
# first index is inclusive (before the :) and last (after the :) is not.
print(z[0:2])
(3, 7)
# everything up to but not including index 3
print(z[:3])
(3, 7, 4)
负索引也OK
print(z[-4:-1])
(3, 7, 4)
元组是不可改变的
元组是不可变的,这意味着在初始化元组之后,不可能更新元组中的单个项。正如您在下面的代码中所看到的,您无法更新或更改元组项的值(这与可变的Python列表不同)。
但可以采用现有元组的一部分来创建新的元组
# Initialize tuple
tup1 = ('Python', 'SQL')
# Initialize another Tuple
tup2 = ('R',)
# Create new tuple based on existing tuples
new_tuple = tup1 + tup2;
print(new_tuple)
('Python', 'SQL', 'R')
Tuple方法
首先初始化一个元组
# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)
index 方法(索引)
index方法返回对应值的第一个索引
print(animals.index('lama'))
0
count 方法(计数)
count方法返回值在元组中出现的次数。
print(animals.count('lama'))
2
遍历元组
您可以使用for循环遍历元组的项目
for item in ('lama', 'sheep', 'lama', 48):
print(item)
lama
sheep
lama
48
元组拆包
元组对序列解包非常有用
x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))
Value of x is 7, the value of y is 10.
枚举
枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
print(index,friend)
(0, 'Steve')
(1, 'Rachel')
(2, 'Michael')
(3, 'Monica')
元组相对列表的优势:
列表和元组是标准Python数据类型,用于在序列中存储值。元组是不可变的,而列表是可变的。以下是元组列表的一些其他优点
组比列表更快。如果你要定义一组常量值,那么你将要做的就是迭代它,使用元组而不是列表。可以使用timeit库部分测量性能差异,该库允许您为Python代码计时。
下面的代码为每个方法运行代码100万次,并输出所花费的总时间(以秒为单位)。
import timeit
print('Tuple time: ', timeit.timeit('x=(1,2,3,4,5,6,7,8,9,10,11,12)', number=1000000))
print('List time: ', timeit.timeit('x=[1,2,3,4,5,6,7,8,9,10,11,12]', number=1000000))
Tuple time: 0.0175598999999238
List time: 0.07908809999980804
元组可以用作字典键
一些元组可以用作字典键(特别是包含不可变值的元组,如字符串,数字和其他元组)。列表永远不能用作字典键,因为列表不是不可变的
bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
print(bigramsTupleDict)
{('this', 'is'): 23, ('is', 'a'): 12, ('a', 'sentence'): 2}
列表不可以用作字典键
元组可以是集合中的值
graphicDesigner = {('this', 'is'),
('is', 'a'),
('a', 'sentence')}
print(graphicDesigner)
{('a', 'sentence'), ('this', 'is'), ('is', 'a')}
列表不可以是集合中的值
exp: 用Python生成斐波那契序列
Fibonacci序列是一个整数序列,其特征在于前两个之后的每个数字是前两个数字的总和。根据定义,Fibonacci序列中的前两个数字是1和1,或0和1,具体取决于所选择的序列起点,以及每个后续数字是前两个数字的总和。
print(1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
1 1 2 3 5 8 13 21 34 55
1.使用循环,编写一个Python程序,打印出前10个Fibonacci数
# Note, there are better ways to code this which I will go over in later videos
a,b = 1,1
for i in range(10):
print("Fib(a): ", a, "b is: ", b)
a,b = b,a+b
Fib(a): 1 b is: 1
Fib(a): 1 b is: 2
Fib(a): 2 b is: 3
Fib(a): 3 b is: 5
Fib(a): 5 b is: 8
Fib(a): 8 b is: 13
Fib(a): 13 b is: 21
Fib(a): 21 b is: 34
Fib(a): 34 b is: 55
Fib(a): 55 b is: 89