python快速入门【二】----常见的数据结构
python入门合集:
python快速入门【三】-----For 循环、While 循环
python快速入门【二】----常见的数据结构
字典
字典是将键(key)映射到值(value)的无序数据结构。值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组。
示例
字典:我们查找的单词是key,查找的定义是值
In [111]
# 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'}
In [112]
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'}
访问字典中的值
In [113]
# Finding out the meaning of the word marathon
# dictionary[key]
webstersDict['marathon']
'a running race that is about 26 miles'
更新字典
In [114]
# 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'
In [115]
# 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.'}
In [116]
# 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.'}
不是所有东西都可以当作Key
下方是错误用法示例
In [117]
webstersDict[['sock']] = 'a short stocking usually reaching to the calf or just above the ankle.'
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-117-95ef7f324c79> in <module>() ----> 1 webstersDict[['sock']] = 'a short stocking usually reaching to the calf or just above the ankle.' TypeError: unhashable type: 'list'
使用get()方法返回给定键的值
你会明白为什么这在字数统计任务中如此有价值
In [118]
# incorporate into get example and such below.
storyCount = {'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
In [119]
storyCount
{'Michael': 12, 'is': 100, 'runs': 5, 'the': 90}
In [120]
# key error for keys that do not exist
storyCount['run']
---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-120-7457d9dbff5f> in <module>() 1 # key error for keys that do not exist ----> 2 storyCount['run'] KeyError: 'run'
In [121]
# 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
In [122]
# When you dont set default value for key that doesnt exist,
# it defaults to none
print(storyCount.get('run'))
None
In [123]
# Making default value for key that doesn't exist 0.
print(storyCount.get('run', 0))
0
删除键,但同时可以返回值
In [124]
count = storyCount.pop('the')
print(count)
90
遍历字典
In [125]
# return keys in dictionary
print(storyCount.keys())
# return values in dictionary
print(storyCount.values())
['is', 'runs', 'Michael']
[100, 5, 12]
In [126]
# iterate through keys
for key in storyCount:
print(key)
is
runs
Michael
In [127]
# iterate through keys and values
for key, value in webstersDict.items():
print(key, value)
('person', 'a human being, whether an adult or child')
('run', 'to move with haste; act quickly')
('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.')
('marathon', 'a running race that is about 26 miles')
('shirt', 'a long- or short-sleeved garment for the upper part of the body')
元组
元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。 元组使用括号,而列表使用方括号。
初始化一个元组
有两种方法可以初始化空元组。您可以通过让()没有值来初始化空元组
In [69]
# Way 1
emptyTuple = ()
您还可以使用元组函数初始化空元组。
In [70]
# Way 2
emptyTuple = tuple()
可以通过用逗号分隔值的序列来初始化具有值的元组。
In [72]
# way 1
z = (3, 7, 4, 2)
# way 2 (tuples can also can be created without parenthesis)
z = 3, 7, 4, 2
重要的是要记住,如果要创建仅包含一个值的元组,则需要在项目后面添加一个逗号。
In [73]
# tuple with one value
tup1 = ('Michael',)
# tuple with one value
tup2 = 'Michael',
# This is a string, NOT a tuple.
notTuple = ('Michael')
访问元组内的值
元组中的每个值都有一个指定的索引值。值得注意的是,python是一种基于零索引的语言。所有这些意味着元组中的第一个值是索引0。
In [75]
# Initialize a tuple
z = (3, 7, 4, 2)
# Access the first item of a tuple at index 0
print(z[0])
3
Python还支持负索引。负索引从元组结束开始。使用负索引来获取元组中的最后一项有时会更方便,因为您不必知道元组的长度来访问最后一项。
In [76]
# print last item in the tuple
print(z[-1])
2
提醒一下,您也可以使用正索引访问相同的项目(如下所示)。
In [77]
print(z[3])
2
切分元组
切分操作返回包含所请求项的新元组。切分很适合在元组中获取值的子集。对于下面的示例代码,它将返回一个元组,其中包含索引0的对象,而不包括索引2的对象。
In [78]
# 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)
In [80]
# everything up to but not including index 3
print(z[:3])
(3, 7, 4)
负索引也OK
In [81]
print(z[-4:-1])
(3, 7, 4)
元组是不可改变的
元组是不可变的,这意味着在初始化元组之后,不可能更新元组中的单个项。正如您在下面的代码中所看到的,您无法更新或更改元组项的值(这与可变的Python列表不同)。
下方有错误示例
In [83]
z = (3, 7, 4, 2)
z[1] = "fish"
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-83-1ba53bfc5f04> in <module>() 1 z = (3, 7, 4, 2) 2 ----> 3 z[1] = "fish" TypeError: 'tuple' object does not support item assignment
即使元组是不可变的,也可以采用现有元组的一部分来创建新的元组,如下例所示。
In [85]
# 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方法
在开始本节之前,让我们首先初始化一个元组
In [86]
# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)
index 方法(索引)
index方法返回对应值的第一个索引
In [87]
print(animals.index('lama'))
0
count 方法(计数)
count方法返回值在元组中出现的次数。
In [88]
print(animals.count('lama'))
2
遍历元组
您可以使用for循环遍历元组的项目
In [89]
for item in ('lama', 'sheep', 'lama', 48):
print(item)
lama
sheep
lama
48
元组拆包
元组对序列解包非常有用
In [91]
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的开始)和迭代序列获得的值
In [93]
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万次,并输出所花费的总时间(以秒为单位)。
In [1]
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.0192110538482666)
('List time: ', 0.16498994827270508)
元组可以用作字典键
一些元组可以用作字典键(特别是包含不可变值的元组,如字符串,数字和其他元组)。列表永远不能用作字典键,因为列表不是不可变的
In [98]
bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
print(bigramsTupleDict)
{('is', 'a'): 12, ('this', 'is'): 23, ('a', 'sentence'): 2}
列表不可以用作字典键
In [99]
bigramsListDict = {['this', 'is']: 23,
['is', 'a']: 12,
['a', 'sentence']: 2}
print(bigramsListDict)
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-99-834f1c969506> in <module>() ----> 1 bigramsListDict = {['this', 'is']: 23, 2 ['is', 'a']: 12, 3 ['a', 'sentence']: 2} 4 5 print(bigramsListDict) TypeError: unhashable type: 'list'
元组可以是集合中的值
In [50]
graphicDesigner = {('this', 'is'),
('is', 'a'),
('a', 'sentence')}
print(graphicDesigner)
set([('is', 'a'), ('this', 'is'), ('a', 'sentence')])
列表不可以是集合中的值
In [49]
graphicDesigner = {['this', 'is'],
['is', 'a'],
['a', 'sentence']}
print(graphicDesigner)
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-49-008c17adfe8f> in <module>() 1 graphicDesigner = {['this', 'is'], 2 ['is', 'a'], ----> 3 ['a', 'sentence']} 4 print(graphicDesigner) TypeError: unhashable type: 'list'
Task: 用Python生成斐波那契序列
Fibonacci序列是一个整数序列,其特征在于前两个之后的每个数字是前两个数字的总和。根据定义,Fibonacci序列中的前两个数字是1和1,或0和1,具体取决于所选择的序列起点,以及每个后续数字是前两个数字的总和。
In [2]
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数
In [24]
# 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)
python快速入门【二】----常见的数据结构的更多相关文章
- Python快速入门
Python快速入门 一.基础概要 命名:h.py Linux命令行运行:python h.py 注释.数字.字符串: 基本类型只有数字与字符串 #python注释是这样写的 ''' 当然也可以这样 ...
- 2.Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- Python爬虫入门二之爬虫基础了解
1.什么是爬虫 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.想抓取什么?这个由你来控制它咯. ...
- 转 Python爬虫入门二之爬虫基础了解
静觅 » Python爬虫入门二之爬虫基础了解 2.浏览网页的过程 在用户浏览网页的过程中,我们可能会看到许多好看的图片,比如 http://image.baidu.com/ ,我们会看到几张的图片以 ...
- python快速入门及进阶
python快速入门及进阶 by 小强
- Python快速入门PDF高清完整版免费下载|百度云盘
百度云盘:Python快速入门PDF高清完整版免费下载 提取码:w5y8 内容简介 这是一本Python快速入门书,基于Python 3.6编写.本书分为4部分,第一部分讲解Python的基础知识,对 ...
- 1、Python快速入门(0529)
学习来自马哥教育的视频,感谢马哥 编程语言: 用户: 问题空间 计算机:解决问题 解空间 抽象: 机器代码-->微码编程-->高级语言 (语言的高下级的是根据语言是否被人类容易理解或者更接 ...
- Python快速入门之与C语言异同
代码较长,建议使用电脑阅读本文. 10分钟入门Python 本文中使用的是Python3如果你曾经学过C语言,阅读此文,相信你能迅速发现这两种语言的异同,达到快速入门的目的.下面将开始介绍它们的异同. ...
- Python 爬虫入门(二)——爬取妹子图
Python 爬虫入门 听说你写代码没动力?本文就给你动力,爬取妹子图.如果这也没动力那就没救了. GitHub 地址: https://github.com/injetlee/Python/blob ...
- python快速入门——进入数据挖掘你该有的基础知识
这篇文章是用来总结python中重要的语法,通过这些了解你可以快速了解一段python代码的含义 Python 的基础语法来带你快速入门 Python 语言.如果你想对 Python 有全面的了解请关 ...
随机推荐
- 敏捷编辑器Sublime text 4中文配置Python3开发运行代码环境
敏捷编辑器Sublime text 4中文配置Python3开发运行代码环境 首先来到Win11环境下,进入Sublime text 4官网的下载页面:https://www.sublimetext. ...
- ACM | 动态规划-数塔问题变种题型
前言 数塔问题,又称数字三角形.数字金字塔问题.数塔问题是多维动态规划问题中一类常见且重要的题型,其变种众多,难度遍布从低到高,掌握该类型题目的算法思维,对于攻克许多多维动态规划的问题有很大帮助. 当 ...
- Centos7 kubeadm安装k8s
安装环境准备 关闭防火墙 systemctl stop firewalld systemctl disable firewalld 关闭selinux sed -i 's/enforcing/disa ...
- 【有奖体验】叮!你有一张 3D 卡通头像请查收
立即体验基于函数计算部署[图生图]一键部署3D卡通风格模型: https://developer.aliyun.com/topic/aigc_fc 人工智能生成内容(Artificial Intell ...
- C#开源跨平台的多功能Steam工具箱
前言 作为一名程序员你是否会经常会遇到GitHub无法访问(如下无法访问图片),或者是访问和下载源码时十分缓慢就像乌龟爬行一般.今天分享一款C#开源的.跨平台的多功能Steam工具箱和GitHub加速 ...
- hdu 5547
***题意:4*4数独,要求在同一行同一列不能有相同的数字,另外在2*2的小单元里也不能有相同的数字 思路:DFS暴力搜索, 每个位置填1-4,递归回溯,判断是否符合条件,递归到最后一个位置+1则输出 ...
- CSS3之transition
随着css3不断地发展,越来越多的页面特效可以被实现. 例如当我们鼠标悬浮在某个tab上的时候,给它以1s的渐进变化增加一个背景颜色.渐进的变化可以让css样式变化得不那么突兀,也显得交互更加柔和. ...
- AI伴侣下载
总结 现在网页上很多下载的AI伴侣下载下来都会有些问题或者不能用,如下链接下载的AI伴侣亲测可以使用! (连接后会提示更新,博主没有选择更新,如有需要也可以更新) https://mit-ai2-co ...
- HanLP — 感知机(Perceptron)
感知机(Perceptron)是一个二类分类的线性分类模型,属于监督式学习算法.最终目的: 将不同的样本分本 感知机饮食了多个权重参数,输入的特征向量先是和对应的权重相乘,再加得到的积相加,然后将加权 ...
- 【js】 Object.prototype.toString.call()
1,Object.prototype.toString这个方法的作用是什么 判断数据类型 2,为什么要用这个方法 是因为 js 中 一般的类型判断 对于 null,数组,对象 , 都会返回一样的结 ...