广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python基础3
  • 900
分享到

python基础3

基础python 2023-01-31 07:01:07 900人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

Python基础3 交换:a,b=b,a相当于定义了一个元组t=(b,a)然后将t[0]的值给了a,t[1]的值给了b####字典####定义用花括号集合定义若为空的话,会默认为字典,所以集合不能为空子典只能通过关键字来查找值,因为字典是k

Python基础3


 交换:
a,b=b,a

相当于定义了一个元组t=(b,a)
然后将t[0]的值给了a,t[1]的值给了b





####字典####

定义用花括号

集合定义若为空的话,会默认为字典,所以集合不能为空




子典只能通过关键字来查找值,因为字典是key-value(关键字-值),因此不能通过值来查找关键字
In [1]: dic = {"user1":"123","user2":"234","user3":"789"}
In [3]: dic["234"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-2845b64d96b1> in <module>()
----> 1 dic["234"]

KeyError: '234'




字典是一个无序的数据类型,因此也不能进行索引和切片等操作。
In [1]: dic = {"user1":"123","user2":"234","user3":"789"}

In [2]: dic["user1"]
Out[2]: '123'

In [5]: dic["user2"]
Out[5]: '234'



In [7]: user = ['user1','user2','user3']

In [8]: passwd = ['123','234','456']

In [9]: zip(user,passwd)
Out[9]: [('user1', '123'), ('user2', '234'), ('user3', '456')]

In [10]:

当你有一个用户名单和密码,若使用列表的类型,判断用户是否和密码一致时,就比较麻烦,而使用字典时,只需通过关键子就可以返回相对应的值,(如上例子:当定义一个子典当你搜索user1时,字典类型就会返回该关键字对应的密码,此时只需判断该密码是否匹配即可)



####字典的基本操作###

In [17]: dic.
dic.clear       dic.items       dic.pop         dic.viewitems
dic.copy        dic.iteritems   dic.popitem     dic.viewkeys
dic.fromkeys    dic.iterkeys    dic.setdefault  dic.viewvalues
dic.get         dic.itervalues  dic.update      
dic.has_key     dic.keys        dic.values



字典添加

In [12]: dic
Out[12]: {'user1': '123', 'user2': '234', 'user3': '789'}

In [13]: dic["westos"]='linux'

In [14]: dic
Out[14]: {'user1': '123', 'user2': '234', 'user3': '789', 'westos': 'linux'}

In [15]: dic["hello"]='world'

In [16]: dic            ####由此可以看出字典是无序的,在添加时,并不会按照顺序往后添加####
Out[16]:
{'hello': 'world',
 'user1': '123',
 'user2': '234',
 'user3': '789',
 'westos': 'linux'}

In [17]:


字典更新


In [22]: dic
Out[22]: {'hello': 'world', 'user1': '123', 'user2': '234', 'user3': '789'}

In [23]: dic["user1"]="redhat"        ###可直接通过赋值对关键字进行更新###

In [24]: dic
Out[24]: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}


###或者通过dic.update更新###
In [25]: dic
Out[25]: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}

In [26]: help(dic.update)
Help on built-in function update:

update(...)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
    If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]
(END)


In [28]: dic1={'yunwei':"westos",'user1': 'redhat'}

In [29]: dic.update(dic)
dic   dic1  dict  

In [29]: dic.update(dic1)        ###将dic1中dic所没有的更新给了diC###

In [30]: dic
Out[30]:
{'hello': 'world',
 'user1': 'redhat',
 'user2': '234',
 'user3': '789',
 'yunwei': 'westos'}

In [31]:




####若是关键字相同,而值不同,就将值更新给他####

In [35]: dic
Out[35]: {'hello': 'world'}

In [36]: dic1
Out[36]: {'user1': 'redhat', 'yunwei': 'westos'}

In [37]: dic1["hello"]="hai"

In [38]: dic.update(dic1)

In [39]: dic
Out[39]: {'hello': 'hai', 'user1': 'redhat', 'yunwei': 'westos'}



In [42]: dic.clear()        ###清空dic###

In [43]: dic
Out[43]: {}

In [44]: del(dic)        ###删除dic###

In [45]: dic
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<iPython-input-45-1b445b6ea935> in <module>()
----> 1 dic

NameError: name 'dic' is not defined




####字典的删除####

In [49]: dic1
Out[49]: {'user1': 'redhat', 'yunwei': 'westos'}

In [50]: dic1.pop("user1")        ###指定关键字,删除该关键字和值####
Out[50]: 'redhat'

In [51]: dic1
Out[51]: {'yunwei': 'westos'}

In [52]:



In [74]: dic1.popitem()        ###不指定关键字,随即删除###
Out[74]: ('yunwei', 'westos')



In [77]: dic = {"hello":"123","westos":"linux"}        

In [79]: dic.keys()        ###查看dic的全部关键字###
Out[79]: ['hello', 'westos']

In [80]: dic.values()        ###查看dic的全部值###
Out[80]: ['123', 'linux']



In [82]: dic.get("hello")    ###得到相对应的关键字的值,若关键字不存在,则默认返回none
Out[82]: '123'

In [83]: dic.get("redhat")

In [84]: print dic.get("redhat")
None


In [87]: dic.has_key("hello")        ###查看是否有该关键字,
Out[87]: True

In [88]: dic.has_key("world")
Out[88]: False


dict.fromkeys()            ###可以通过该操作实现去重###

In [89]: dic
Out[89]: {'hello': '123', 'westos': 'linux'}

In [90]: dic.fromkeys([1,2,3,4])
Out[90]: {1: None, 2: None, 3: None, 4: None}

In [91]: dic.fromkeys([1,2,3,4],'hello')
Out[91]: {1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello'}


In [38]: d = {}
In [32]: li = [1,2,3,1,2,3]            ###去重###

In [33]: d.fromkeys(li)
Out[33]: {1: None, 2: None, 3: None}

In [34]: d.fromkeys(li).keys()
Out[34]: [1, 2, 3]



字典的key必须是不可变的数据类型


In [94]: dic = {1:'1',2:'2',1:'a'}

In [95]: dic
Out[95]: {1: 'a', 2: '2'}        ###一个关键字只能对应一个值###

In [96]: for key in dic.keys():        ###逐个遍历key###
   ....:     print "key=%s" % key
   ....:
key=1
key=2


In [97]: for value in dic.values():    ###逐个遍历value的值###
    print "value=%s" % value
   ....:     
value=a
value=2


In [98]: for key,value in dic.keys(),dic.values():    ###逐个遍历key -> value 的值#####
   ....:     print "%s -> %s" %(key,value)
   ....:
1 -> 2
a -> 2




In [100]: dic
Out[100]: {1: 'a', 2: '2'}
In [101]: dic.items()            ###以元组的形式一一对应key和value的值###
Out[101]: [(1, 'a'), (2, '2')]

In [102]: for k,v in dic.items():
   .....:     print "%s -> %s" %(k,v)
   .....:
1 -> a
2 -> 2


和list的比较,dict的不同:
1 查找和插入的速度快,字典不会随着key值的增加查找速度减慢
2 占用内存大,浪费空间



小练习:
去掉一个最高分和最低分,并且显示平均值

li = [90,91,67,100,89]


In [103]: li = [90,91,67,100,89]

In [104]: li.sort()        ###排序###

In [105]: li
Out[105]: [67, 89, 90, 91, 100]

In [106]: li.pop()
Out[106]: 100

In [107]: li.pop(0)
Out[107]: 67

In [108]: li
Out[108]: [89, 90, 91]

In [109]: sum(li)/len(li)    ###sum函数求和###
Out[109]: 90

小练习:用字典实现case语句:
!/usr/bin/env python
#coding:utf-8
from __future__ import division
num1 = input("num1:")
oper = raw_input('操作:')
num2 = input('num2:')

dic = {"+":num1+num2,"-":num1-num2,"*":num1*num2,'/':num1/num2}

if oper in dic.keys():
    print dic[oper]



#####函数####


函数名的理解:函数名与变量名类似,其实就是指向一个函数对象的引用;

            给这个函数起了一个“别名”:函数名赋给一个变量


In [5]: sum(li)
Out[5]: 6

In [6]: a = sum        ###将sum的函数名给了a变量,使得a能够进行求和###

In [7]: a(li)
Out[7]: 6

In [8]:
In [8]: sum = abs

In [9]: sum(-1)
Out[9]: 1

In [10]: sum([2,4,5]    ###将abs的函数名给了sum,则sum就不再具有求和的功能###
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-d3c81a94a2a0> in <module>()
----> 1 sum([2,4,5])

TypeError: bad operand type for abs(): 'list'

In [11]: a([2,4,5])
Out[11]: 11



####函数的返回值###

def    hello():
    print "hello"

print hello()            ###该函数没有返回值,只是打印了hello,返回值为none


def    hello():
    return    ”hello“

print hello()            ###该函数有返回值,则返回一个hello###    


####函数在执行过程中一旦遇到return,就执行完毕并且将结果返回,如果没有遇到return,返回值为none###


###定义一个什么也不做的空函数,可以用pass语句,作为一个占位符使得代码先运行起来

def hello():
    return "hello"

def world():
    pass

print hello()
print world()


运行结果:
/usr/bin/python2.7 /home/kiOSk/PyCharmProjects/pythonbasic/10.py
hello
None

Process finished with exit code 0





小练习:将abs的错误显示进行优化###

def my_abs(x):
    if isinstance(x,(int,float)):    ###判断数据类型,是int或是float(也可以是别的类型,看你写的)###
     print   abs(x)
    else:
        print "请输入整型或浮点型的数"


my_abs("a")
my_abs(123)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/11.py
请输入整型或浮点型的数
123

Process finished with exit code 0




小练习:定义一个函数func(name),该函数效果如下:
func('hello')    -> 'Hello'
func('World')    -> 'World'

def func(name):
    print name.capitalize()
name = raw_input("name:")
func(name)


执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/12.py
name:hello
Hello

Process finished with exit code 0


函数的返回值,函数可以返回多个值
小练习:定义一个函数func,传入两个数字,返回两个数字的最大值和平均值


def func(x,y):
    if x>y:
        return x,(x+y)/2
    else:
        return y,(x+y)/2


x=6
y=3
print func(x,y)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/13.py
(6, 4)            ###由此可见,返回多个值,实际上是返回一个元组###

Process finished with exit code 0


###返回的元组的括号可以省略,函数调用接受返回值时,按照位置赋值变量###
def func(x,y):
    if x>y:
        return x,(x+y)/2
    else:
        return y,(x+y)/2


x=6
y=3
avg,maxnum = func(x,y)
print avg,maxnum

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/13.py
6 4

Process finished with exit code 0


###函数的参数###
def power(x,n=2):    ###设定n默认为2,则n为默认参数,x为必选参数###
    return x**n
print power(2)


def power(x,n=2):
    return x**n
print power(2,4)    ###也可以进行多次操作###

####当默认参数和必选参数同时存在时,一定要将必选参数放在默认参数之前###

###设置默认参数时,把变化大的参数放前面,变化小的参数放后面,将变化小的参数设置为默认参数###

def enroll(name,age=22,myclass="westoslinux"):
    print 'name=%s'% name
    print 'age:%d'% age
    print 'class:%s' %myclass

enroll('user1')
enroll('user2',20)
enroll('user3',18,'全能班')

执行结果:
name=user1
age:22
class:westoslinux
name=user2
age:20
class:westoslinux
name=user3
age:18
class:全能班

Process finished with exit code 0


###默认参数必须使不可变的数据类型###
例:
先定义一个函数,传入一个 list,添加一个END 再返回

def fun(li=[]):
    li.append("END")
    return li
print fun([1,2,3])
print fun()
print fun()

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
[1, 2, 3, 'END']
['END']
['END', 'END']        ###因为列表是可变的数据类型,所以在第二次输入print    fun()时,默认参数就不是空,而已经有了一个“END”###

Process finished with exit code 0




更改为:li=None,则此时li的默认值为不可变的数据类型


def fun(li=None):
    if li is None:
        return ['END']
    li.append('END')
    return li
print fun([1,2,3])
print fun()
print fun()


执行结果为:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
[1, 2, 3, 'END']
['END']
['END']

Process finished with exit code 0




####可变参数###
定义参数时,形参可以为*args,使函数可与接受多个参数;
如果想要将一个列表或者元组传入参数,也可以通过*li或*t,将参数传入函数里。

def fun(*args):        ###参数前面一定要加*###
    print type(args)
    return max(args),min(args)
li = [1,42,3,14,58,6]
print fun(*li)        ###传递列表时,前面也要加*###

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
(58, 1)

Process finished with exit code 0

###若传递列表时,不加*号###

def fun(*args):
    print type(args)
    return max(args),min(args)
li = [1,42,3,14,58,6]
print fun(li)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
([1, 42, 3, 14, 58, 6], [1, 42, 3, 14, 58, 6])

Process finished with exit code 0


###传递多个数###

def fun(*args):
    print type(args)
    return max(args),min(args)

print fun(1,42,3,14,58,6)

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
(58, 1)

Process finished with exit code 0




###关键字可变参数###

def enroll(name,age=22,**kwargs):
    print 'name=%s'% name
    print 'age:%d'% age
    for k,w in kwargs.items():
        print '%s:%s'%(k,w)
    print type(kwargs)

enroll('user3',myclass='运维班')

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
name=user3
age:22
myclass:运维班
<type 'dict'>

Process finished with exit code 0







参数定义优先级:必选参数>默认参数>可变参数>关键字参数

*arg,可变参数接受的是元组
**kwargs,关键字参数,接受的是字典



###局部变量,只在函数内部生效,全局变量,在整个代码中生效###



--结束END--

本文标题: python基础3

本文链接: https://www.lsjlt.com/news/192102.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python基础3
    python基础3 交换:a,b=b,a相当于定义了一个元组t=(b,a)然后将t[0]的值给了a,t[1]的值给了b####字典####定义用花括号集合定义若为空的话,会默认为字典,所以集合不能为空子典只能通过关键字来查找值,因为字典是k...
    99+
    2023-01-31
    基础 python
  • python学习-3 python基础-
    1.基础知识 ~后缀名是可以是任意的 ~导入模块时,如果不是.py就会报错 =》》所以尽量后缀名携程.py 2.执行方式 -python解释器 3.   #!/usr/bin/env python          -----------...
    99+
    2023-01-31
    基础 python
  • Python基础笔记3
    1.Python内置了很多有用的函数,我们可以直接调用。要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档:http://docs.python.org/3/libra...
    99+
    2023-01-31
    基础 笔记 Python
  • 3. Python基础语法
    我们在文言文中经常会看到注释,注释可以帮助读者对文章的理解。代码中的注释也是一样,优秀的代码注释可以帮助读者对代码的理解。当然在代码编写过程中,注释的使用不一定只是描述一段代码,也可能的是对代码的调试。 Python注释一共有# 、'''...
    99+
    2023-01-31
    语法 基础 Python
  • python之路,Python基础篇3
    1、set 无序,不重复序列、可嵌套 2、函数 ==》 定义函数,函数体不执行,只有调用函数时,函数体才执行 1、def 2、名字 3、函数体 4、返回值 5、参数 普通参数 指定参数 默认参数 动态参数 ...
    99+
    2023-01-31
    之路 基础 python
  • python之路-基础篇3
    作业:1、每周写一篇博客2、编写登录接口     输入用户名密码     认证成功后显示欢迎信息     输错三次后锁定3、多级菜单     三级菜单     可依次选择进入各子菜单     所需新知识点:列表、字典data = { "水...
    99+
    2023-01-31
    之路 基础 python
  • python基础3——运算符
    注: from future import division <---除法运算中python2导入此模块,除不尽时,小数部分也会显示,python3中不需要导入 1'''----------运算符 + 、—、*、/、%、*--...
    99+
    2023-01-31
    运算符 基础 python
  • python基础学习3----列表
    一.字符格式化输出 占位符 %s s = string 字符串           %d d = digit 整数           %f f = float 浮点数 name = input("Name:") age = int...
    99+
    2023-01-30
    基础 列表 python
  • Python基础语法介绍(3)
    基本概念、特性 顺序存储相同/不同类型的元素 定义:使用()将元素括起来,元素之间用“,”括开 特性:不可变,不支持添加,修改,删除等操作 查询:通过下标查询元组指定位置的元素 其他 空元组定义:non_tuple = () 只包含一...
    99+
    2023-01-31
    语法 基础 Python
  • python基础(3)—— 程序结构
        python和其他的编程语言一样,也有三种程序结构。顺序结构,选择结构,循环结构。1.顺序结构    顺序结构按照顺序执行程序,不做过多解释。2.选择结构    2.1 if 语句        if condition:     ...
    99+
    2023-01-31
    结构 基础 程序
  • VII Python(3)基础知识(if
    VII Python(3)基础知识(if、while、for、iterator、generator、文件、pickle) 表达式和语句:常用的表达式操作符:算术运算:+,-,*,/,//截断除法,%,**幂运算逻辑运算:x or y,x a...
    99+
    2023-01-31
    基础知识 VII Python
  • javascript基础-3
    一、Browser对象 <一>、window对象 1.window.尺寸 当ie>=9时: window.innerHeight/outHeightwindow.innerWidth/outWidth 当ie=8,7,...
    99+
    2023-01-31
    基础 javascript
  • Linux基础(3)
    1、列出当前系统上所有已经登录的用户的用户名,注意:同一个用户登录多次,则只显示一次即可    who | cut -d '' -f1 |sort |uniq2、列出最后登录到当前系统的用户的相关信息。    last |head -1 3...
    99+
    2023-01-31
    基础 Linux
  • php基础3
    php基础31、post和get可用于发送和接受表单的信息2、post和get在处理表单时候都创建数组array,数组以键值对形式,表单元素名做键,文本框内容做值3、GET和POST被视作$_GET 和 $_POST 他们是超全局变量,可以...
    99+
    2023-01-31
    基础 php
  • 第1章 python 基础语法(3)
    =================目录==================1.8 字典1.9 字典练习2.0/2.1 流程控制-if条件判断 ======================================= dic={}字典是...
    99+
    2023-01-31
    语法 基础 python
  • Python 3基础教程24-读取csv
           本文来介绍用Python读取csv文件。什么是csv(Comma-Separated Values),也叫逗号分割值,如果你安装了excel,默认会用excel打开csv文件。 1. 我们先制作一个csv文件,example...
    99+
    2023-01-31
    基础教程 Python csv
  • Python 基础 - 3 常用数值类型
    参考: Python 基础 - 0 前言 Built-in Types Python 数值类型包括整型(integer),浮点型(floating point number)和复数(complex number),并且,布尔型(...
    99+
    2023-01-31
    数值 常用 类型
  • Linux基础篇之五基础命令 ---- 3
    在linux中,我们经常需要查找某些文件,以及文件所在目录等。那么我们需要用到一些基本的文件查找类命令。文件查找命令主要有以下几个:·which    查看命令或可执...
    99+
    2022-10-18
  • docker-3 基础命令
    创建镜像创建镜像的方法有三种:基于已有的容器创建基于本地模板导入基于dockerfile基于已有的容器创建主要使用docker commit 命令,命令格式:docker commit [OPTIONS] CONTAINER [REPOSI...
    99+
    2023-01-31
    命令 基础 docker
  • linux命令基础(3)
    find是最常见和最强大的查找命令,你可以用它找到任何你想找的文件。find的使用格式如下:find <指定目录> <指定条件> <指定动作>- <指定目录>: 所要搜索的目录及其所有子目录。...
    99+
    2023-01-31
    命令 基础 linux
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作