python--[基础]

用户交互

Linux(输出)

1
2
3
$ python
>>> print("Hello World!")
Hello World!

      print是一个常用函数,其功能就是输出括号中得字符串。(在Python 2.x中,print还可以是一个关键字,可写成print ‘Hello World!’)
写入以下内容,保存并且退出。

1
2
3
4
5
6
7
8
$ cat HelloWorld.py
#!/usr/bin/env python #必须声明是什么解释器来解释此脚本
print("Hello World!")
$ python HelloWorld.py #运行
Hello World!
$ chmod +x HelloWorld.py #授权并执行
$ ./HelloWorld.py
Hello World!

      Python提供了一个input(),可以让用户输入字符串,并存放到一个变量里。比如输入用户的名字:

1
2
3
4
5
>>> name = input('您的名字:')
您的名字:adair
>>> name
'adair'
>>>

      Python2.7下的raw_input与input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> type(raw_input)
<type 'builtin_function_or_method'>
>>> type(input)
<type 'builtin_function_or_method'>
>>> name=raw_input("Please input your name:")
Please input your name:Adair
>>> print(name)
Adair
>>> name1=input("Please input your name:")
Please input your name:Adair
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'Adair' is not defined
>>> n="Adair"
>>> name1=input("Please input your name:")
Please input your name:n
>>> print(name1)
Adair

注意看python2.7在执行input函数式我们第一次输入Adair是有报错的,然后我重新定义一个变量n赋值为Adair然后在执行name1=input(“Please input your name:”)输入n把n的值传入了,没有报错,也可以正常打印,说明一个问题在Python2.7中input里你传入的参数都会被认为是变量,所以重新定义就不会报错

实例:打印用户输入用户名和密码

1
2
3
4
5
6
7
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import getpass #导入模块
i1 = raw_input("UserName:")
i2 = getpass.getpass("PassWord:")
print(i1)
print(i2)

注释

单行注释

1
注释符号#

例子:

1
#此处为注释内容

多行注释

1
注释符号:''' '''

例子:

1
2
3
4
5
'''
注释1
注释2
注释3
'''

      同样的Python注释语句,可以采用 单引号(‘)、双引号(”)、三单双引号(”””),被注释的语句是不被执行的。

行与缩进

      学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。
      前面我们在写用户交互程序的时候已经说到了缩进在 python 语言中的重要性,现在我们再来总结一下 Python 缩进的规则:
      Python 是强制缩进的语言,它通过缩进来确定一个新的逻辑层次的开始和结束,这也是python 语言的最重要的特色之一
      同一逻辑层次级别的代码缩进必须保持一致
      顶层逻辑级别的代码必须不能有缩进(新行的开始不能有空格)
      整个程序的缩进风格应保持一致,一般为 4 个空格或 2 个空格,官方的推荐是用 4 个空格,当然用 tab 键也可以,但是在 Windows 上的 tab 键和 Linux 上的不一致,会导致你在Windows 上开发的程序 copy 到 Linux 上后运行出错,所以还是建议用 4 个空格。

变量与赋值

变量

      整个程序的缩进风格应保持一致,一般为在计算机中,变量就是用来在程序运行期间存储各种需要临时保存可以不断改变的数据的标识符,一个变量应该有一个名字,并且在内存中占据一定的存储单元,在该存储单元中存放变量的值。请注意区分变量名和变量值这两个不同的概念,看下图:
Alt text
声明变量

1
2
3
>>> name = 'adair'
>>> name
'adair'

声明一个变量为name 值为:adair
查看变量内存地址:

1
2
>>> id(name)
3088793757712

常量

      刚才说到了变量,还有一概念就是常量,所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在 Python 中,通常用全部大写的变量名表示常量:
PI=3.14159265359
      但事实上 PI 仍然是一个变量, 根本没有任何机制保证 不会被改变,所以,用全部大写的变量名表示常量只是一个习惯上的用法,如果你一定要改变变量PI的值,也没人能拦住你。

变量的命名规则

  • 变量名只能是字母,数字或下划线的任意组合
  • 变量名的第一个字符不能是数字
  • 以下关键字不能声明为变量名

不可定义的变量

      以下关键字不能声明为变量名(keyword模块,可以输出当前版本的所有关键字)

1
2
3
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

数据类型

数字

int (整数型)
      在32位机器上,整数的位数为32位,取值范围为-231~231-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-263~263-1,即-9223372036854775808~9223372036854775807


float (浮点型)
      浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下 的一位表示符号。


long(长整型)
      跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

布尔值

      布尔值和布尔代数的表示完全一致,一个布尔值只有True、False两种值,要么是True,要么是False,在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过布尔运算计算出来:

1
2
3
4
>>> True
True
>>> False
False

字符串

      字符串类型是python的序列类型,他的本质就是字符序列,而且python的字符串类型是不可以改变的,你无法将原字符串进行修改,但是可以将字符串的一部分复制到新的字符串中,来达到相同的修改效果。

使用引号创建字符串

      创建字符串类型可以使用单引号或者双引号又或者三引号来创建,实例如下:

  • 单引号

    1
    2
    3
    4
    >>> name = 'adair'
    >>> type(name)
    <class 'str'>
    >>>
  • 双引号

    1
    2
    3
    4
    >>> name = "adair"
    >>> type(name)
    <class 'str'>
    >>>
  • 三引号

    1
    2
    3
    >>> name = """adair"""
    >>> type(name)
    <class 'str'>

字符串所具备的方法

  • capitalize(self):
    把值得首字母变大写

    1
    2
    3
    >>> name = 'adair'
    >>> name.capitalize()
    'Adair'
  • center(self, width, fillchar=None):
    内容居中,width:字符串的总宽度;fillchar:填充字符,默认填充字符为空格。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # 定义一个字符串变量,名为"name",内容为"hello word"
    >>> name = "hello word"
    # 输出这个字符串的长度,用len(value_name)
    >>> len(name)
    10
    # 字符串的总宽度为10,填充的字符为"*"
    >>> name.center(10,"*")
    'hello word'
    # 如果设置字符串的总长度为11,那么减去字符串长度10还剩下一个位置,这个位置就会被*所占用
    >>> name.center(11,"*")
    '*hello word'
    # 是从左到右开始填充
    >>> name.center(12,"*")
    '*hello word*'
  • count(self, sub, start=None, end=None):
    sub –> 搜索的子字符串
    start –> 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
    end –> 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
    用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置。

    1
    2
    3
    4
    5
    6
    >>> name="hello word"
    >>> name.count("l") # 默认搜索出来的"l"是出现过两次的
    2
    # 如果指定从第三个位置开始搜索,搜索到第六个位置,"l"则出现过一次
    >>> name.count("l",3,6)
    1
  • encode(self, encoding=None, errors=None):
    编码,针对unicode

    1
    2
    3
    4
    # 定义一个变量内容为中文
    temp = "中文"
    # 把变量的字符集转化为UTF-8
    temp_unicode = temp.decode("utf-8")
  • endswith(self, suffix, start=None, end=None):
    suffix –> 后缀,可能是一个字符串,或者也可能是寻找后缀的tuple。
    start –> 开始,切片从这里开始。
    end –> 结束,片到此为止。
    于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    >>> string="hello word"
    # 判断字符串中是否已"d"结尾,如果是则返回"True"
    >>> string.endswith("d")
    True
    # 判断字符串中是否已"t"结尾,不是则返回"False"
    >>> string.endswith("t")
    False
    # 制定搜索的位置,实则就是从字符串位置1到7来进行判断,如果第七个位置是"d",则返回True,否则返回False
    >>> string.endswith("d",1,7)
    False
  • find(self, sub, start=None, end=None):
    str –> 指定检索的字符串
    beg –> 开始索引,默认为0。
    end –> 结束索引,默认为字符串的长度。
    检测字符串中是否包含子字符串str,如果指定beg(开始)和end(结束)范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

    1
    2
    3
    4
    5
    6
    7
    >>> string="hello word"
    # 返回`o`在当前字符串中的位置,如果找到第一个`o`之后就不会再继续往下面寻找了
    >>> string.find("o")
    4
    # 从第五个位置开始搜索,返回`o`所在的位置
    >>> string.find("o",5)
    7
  • index(self, sub, start=None, end=None):
    str –> 指定检索的字符串
    beg –> 开始索引,默认为0。
    end –> 结束索引,默认为字符串的长度。
    检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> string="hello word"
    # 返回字符串所在的位置
    >>> string.index("o")
    4
    # 如果查找一个不存在的字符串那么就会报错
    >>> string.index("a")
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: substring not found
  • isalnum(self):
    法检测字符串是否由字母和数字组成,如果string至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False

    1
    2
    3
    4
    5
    6
    7
    8
    >>> string="hes2323"
    # 如果存在数字或字母就返回`True`,否则返回`False`
    >>> string.isalnum()
    True
    # 中间有空格返回的就是False了
    >>> string="hello word"
    >>> string.isalnum()
    False
  • isalpha(self):
    检测字符串是否只由字母组成。

    1
    2
    3
    4
    5
    6
    7
    8
    # 如果全部都是字母就返回`True`
    >>> string="helloword"
    >>> string.isalpha()
    True
    # 否则就返回False
    >>> string="hes2323"
    >>> string.isalpha()
    False
  • isdigit(self):
    检测字符串是否只由数字组成

    1
    2
    3
    4
    5
    6
    7
    # 如果变量里面都是数字就返回`True`,否则就返回`False`
    >>> string="hes2323"
    >>> string.isdigit()
    False
    >>> string="2323"
    >>> string.isdigit()
    True
  • islower(self):
    检测字符串是否由小写字母组成

    1
    2
    3
    4
    5
    6
    7
    # 如果变量内容全部都是小写字母就返回`True`,否则就返回`False`
    >>> string="hesasdasd"
    >>> string.islower()
    True
    >>> string="HelloWord"
    >>> string.islower()
    False
  • isspace(self):
    检测字符串是否只由空格组成

    1
    2
    3
    4
    5
    6
    7
    # 如果变量内容由空格来组成,那么就返回`True`否则就返回`False`
    >>> string=" "
    >>> string.isspace()
    True
    >>> string="a"
    >>> string.isspace()
    False
  • istitle(self):
    检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

    1
    2
    3
    4
    5
    6
    7
    # 如果变量的内容首字母是大写并且其他字母为小写,那么就返回`True`,否则会返回`False`
    >>> string="Hello Word"
    >>> string.istitle()
    True
    >>> string="Hello word"
    >>> string.istitle()
    False
  • isupper(self):
    检测字符串中所有的字母是否都为大写。

    1
    2
    3
    4
    5
    6
    7
    # 如果变量值中所有的字母都是大写就返回`True`,否则就返回`False`
    >>> string="hello word"
    >>> string.isupper()
    False
    >>> string="HELLO WORD"
    >>> string.isupper()
    True
  • join(self, iterable):
    将序列中的元素以指定的字符连接生成一个新的字符串。

    1
    2
    3
    >>> string=("a","b","c")
    >>> '-'.join(string)
    'a-b-c'
  • ljust(self, width, fillchar=None):
    width –> 指定字符串长度
    fillchar –> 填充字符,默认为空格
    返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

    1
    2
    3
    4
    5
    6
    >>> string="helo word"
    >>> len(string)
    9
    # 定义的长度减去字符串的长度,剩下的就开始填充
    >>> string.ljust(15,'*')
    'helo word******'
  • lower(self):
    转换字符串中所有大写字符为小写。

    1
    2
    3
    4
    # 把变量里的大写全部转换成小写
    >>> string="Hello WORD"
    >>> string.lower()
    'hello word'
  • lstrip(self, chars=None):
    chars –> 指定截取的字符
    用于截掉字符串左边的空格或指定字符

    1
    2
    3
    4
    # 从左侧开始删除匹配的字符串
    >>> string="hello word"
    >>> string.lstrip("hello ")
    'word'
  • partition(self, sep):
    str –> 指定的分隔符
    用来根据指定的分隔符将字符串进行分割,如果字符串包含指定的分隔符,则返回一个3元的tuple,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

    1
    2
    3
    4
    # 返回的是一个元组类型
    >>> string="www.ansheng.me"
    >>> string.partition("ansheng")
    ('www.', 'ansheng', '.me')
  • replace(self, old, new, count=None):
    old –> 将被替换的子字符串
    new –> 新字符串,用于替换old子字符串
    count –> 可选字符串, 替换不超过count次

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    把字符串中的 old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过max次
    >>> string="www.ansheng.me"
    # 把就字符串`www.`换成新字符串`https://`
    >>> string.replace("www.","https://")
    'https://ansheng.me'
    # 就字符串`w`换成新字符串`a`只替换`2`次
    >>> string.replace("w","a",2)
    'aaw.ansheng.me'
    ```python
    * rfind(self, sub, start=None, end=None):
    str –> 查找的字符串
    beg –> 开始查找的位置,默认为0
    end –> 结束查找位置,默认为字符串的长度
    返回字符串最后一次出现的位置,如果没有匹配项则返回-1
    ```python
    >>> string="hello word"
    # rfind其实就是反向查找
    >>> string.rfind("o")
    7
    # 指定查找的范围
    >>> string.rfind("o",0,6)
    4
  • rindex(self, sub, start=None, end=None):
    str –> 查找的字符串
    beg –> 开始查找的位置,默认为0
    end –> 结束查找位置,默认为字符串的长度

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    返回子字符串str在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
    >>> string="hello word"
    # 反向查找索引
    >>> string.rindex("o")
    7
    # 如果没有查找到就报错
    >>> string.rindex("a")
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: substring not found
  • rjust(self, width, fillchar=None):
    width –> 指定填充指定字符后中字符串的总长度
    fillchar –> 填充的字符,默认为空格

    1
    2
    3
    4
    5
    6
    7
    8
    返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。
    >>> string="hello word"
    >>> len(string)
    10
    >>> string.rjust(10,"*")
    'hello word'
    >>> string.rjust(12,"*")
    '**hello word'
  • rsplit(self, sep=None, maxsplit=None):
    str--> 分隔符,默认为空格 *num* –> 分割次数
    从右到左通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个子字符串

    1
    2
    3
    4
    5
    >>> string="www.ansheng.me"
    >>> string.rsplit(".",1)
    ['www.ansheng', 'me']
    >>> string.rsplit(".",2)
    ['www', 'ansheng', 'me']
  • rstrip(self, chars=None):
    chars –> 指定删除的字符
    删除string字符串末尾的指定字符(默认为空格).

    1
    2
    3
    4
    # 从尾部开始匹配删除
    >>> string="hello word"
    >>> string.rstrip("d")
    'hello wor'
  • split(self, sep=None, maxsplit=None):
    str--> 分隔符,默认为空格 *num* –> 分割次数
    从左到右通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个子字符串

    1
    2
    3
    4
    5
    6
    7
    >>> string="www.ansheng.me"
    # 指定切一次,以`.`来分割
    >>> string.split(".",1)
    ['www', 'ansheng.me']
    # 指定切二次,以`.`来分割
    >>> string.split(".",2)
    ['www', 'ansheng', 'me']
  • splitlines(self, keepends=False):
    num –> 分割行的次数
    按照行分隔,返回一个包含各行作为元素的列表,如果num指定则仅切片num个行.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    # 定义一个有换行的变量,`\n`可以划行
    >>> string="www\nansheng\nme"
    # 输出内容
    >>> print(string)
    www
    ansheng
    me
    # 把有行的转换成一个列表
    >>> string.splitlines(1)
    ['www\n', 'ansheng\n', 'me']
  • startswith(self, prefix, start=None, end=None):
    str –> 检测的字符串
    strbeg –> 可选参数用于设置字符串检测的起始位置
    strend –> 可选参数用于设置字符串检测的结束位置
    检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

    1
    2
    3
    4
    5
    >>> string="www.ansheng.me"
    >>> string.startswith("www")
    True
    >>> string.startswith("www",3)
    False
  • strip(self, chars=None):
    chars –> 移除字符串头尾指定的字符
    移除字符串头尾指定的字符(默认为空格)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    >>> string=" www.ansheng.me "
    >>> string
    ' www.ansheng.me '
    # 删除空格
    >>> string.strip()
    'www.ansheng.me'
    >>> string="_www.ansheng.me_"
    # 指定要把左右两边的"_"删除掉
    >>> string.strip("_")
    'www.ansheng.me'
  • swapcase(self):
    用于对字符串的大小写字母进行转换,大写变小写,小写变大写

    1
    2
    3
    >>> string="hello WORD"
    >>> string.swapcase()
    'HELLO word'
  • title(self):
    返回”标题化”的字符串,就是说所有单词都是以大写开始,其余字母均为小写。

    1
    2
    3
    >>> string="hello word"
    >>> string.title()
    'Hello Word'
  • translate(self, table, deletechars=None):
    table –> 翻译表,翻译表是通过maketrans方法转换而来
    deletechars –> 字符串中要过滤的字符列表
    根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。

  • upper(self):
    将字符串中的小写字母转为大写字母

    1
    2
    3
    >>> string="hello word"
    >>> string.upper()
    'HELLO WORD'
  • zfill(self, width):
    width –> 指定字符串的长度。原字符串右对齐,前面填充0
    返回指定长度的字符串,原字符串右对齐,前面填充0

格式化字符串例子:

1
2
3
4
5
>>> string="hello word"
>>> string.zfill(10)
'hello word'
>>> string.zfill(20)
'0000000000hello word'

输出结果:

1
2
3
4
5
6
7
8
9
10
"C:\Program Files\Python35\python.exe" C:/Users/Administrator/PycharmProjects/S12/day1/string_format.py
name:adair
age:21
job:engineer
Information of adair:
Name:adair
Age:21
Job:engineer
Process finished with exit code 0

第二种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#/usr/bin/env python
#-*- coding:utf-8-*-
__author__ = "Jie"
name = input("name:")
age = input("age:")
job = input("job:")
msg = '''
Information of %s:
Name:%s
Age:%s
Job:%s
''' %(name,name,age,job)
print(msg)

输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
"C:\Program Files\Python35\python.exe" C:/Users/Administrator/PycharmProjects/S12/day1/string_format.py
name:zhujie
age:21
job:engineer
Information of zhujie:
Name:zhujie
Age:21
Job:engineer
Process finished with exit code 0

Ps:字符串是%s;整数%d;浮点数%f

列表

      Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。

创建列表

比如列出各类编程语言:

1
2
3
>>> lang1=['python','java','php','c++']
>>> lang1
['python', 'java', 'php', 'c++']

支持的方法

      用dir()函数可以查看此列表能使用的方法

1
2
>>> dir(lang1)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

索引

      .index用索引来访问list中每一个位置的元素,索引是从0开始的

1
2
3
4
5
6
7
>>> lang1=['python','java','php','c++']
>>> lang1
['python', 'java', 'php', 'c++']
>>> lang1.index('php')
2
>>> lang1.index('python')
0

切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> lang1=['python','java','php','c++']
>>> lang1[1:2]
['java']
>>> lang1[0:3]
['python', 'java', 'php']
>>> lang1[:3]
['python', 'java', 'php']
>>> lang1[:-1]
['python', 'java', 'php']
>>> lang1[:1]
['python']
>>> lang1[-1]
'c++'
>>> lang1[-2]
'php'

追加

      .append(self, p_object)用于在列表末尾添加新的对象,obj – 添加到列表末尾的对象,该方法无返回值,但是会修改原来的列表。

1
2
3
>>> lang1.append('vue')
>>> lang1
['python', 'java', 'php', 'c++', 'vue']

删除最后一个元素

      .pop(self, index=None)用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,index– 可选参数,要移除列表元素的对象,该方法返回从列表中移除的元素对象,可以通过pop(index)指定删除类似remove

1
2
3
4
5
6
>>> lang1.pop()
'vue'
>>> lang1.pop(0)
'python'
>>> lang1
['java', 'php', 'c++']

指定删除

      .remove(self, value)用于移除列表中某个值的第一个匹配项,value – 列表中要移除的对象,该方法没有返回值但是会移除两种中的某个值的第一个匹配项。

1
2
3
4
5
>>> lang1
['java', 'php', 'c++']
>>> lang1.remove("php")
>>> lang1
['java', 'c++']

指定插入

      .insert(self, index, p_object)用于将指定对象插入列表,index – 对象obj需要插入的索引位置,obj – 要插入列表中的对象,该方法没有返回值,但会在列表指定位置插

1
2
3
>>> lang1.insert(2,"nodejs")
>>> lang1
['java', 'c++', 'nodejs']

次数统计

      .count用于统计某个元素在列表中出现的次数,value – 列表中统计的对象,返回元素在列表中出现的次数。

1
2
>>> lang1.count('c++')
1

反向存放

      .reverse(self)用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序。

1
2
3
>>> lang1.reverse()
>>> lang1
['nodejs', 'c++', 'java']

合并

      .extend(self, iterable)用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),seq – 元素列表,该方法没有返回值,但会在已存在的列表中添加新的列表内容

1
2
3
4
5
>>> list1=[1,2,3,4,5]
>>> list2=['a','b','c','d','f']
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'f']

排序

      .sort(self, cmp=None, key=None, reverse=False)用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数,该方法没有返回值,但是会对列表的对象进行排序。

1
2
3
4
>>> list1 = [1,2,3,4,5,7,8,6,5]
>>> list1.sort()
>>> list1
[1, 2, 3, 4, 5, 5, 6, 7, 8]

元组

      Python的元组与列表类似,不同之处在于元组的元素不能修改。
      元组使用小括号,列表使用方括号。
      元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

创建元组

1
2
3
>>> boy=('mayun','aobama','liyanhong','mahuateng')
>>> boy
('mayun', 'aobama', 'liyanhong', 'mahuateng')

支持的方法

1
2
>>> dir(boy)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

索引

1
2
3
4
5
>>> boy.index('mayun')
0
>>> boy.index('mahuateng')
3
>>>

切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> boy[1:2]
('aobama',)
>>> boy[1:3]
('aobama', 'liyanhong')
>>> boy[0:3]
('mayun', 'aobama', 'liyanhong')
>>> boy[:3]
('mayun', 'aobama', 'liyanhong')
>>> boy[:-1]
('mayun', 'aobama', 'liyanhong')
>>> boy[:-2]
('mayun', 'aobama')
>>> boy[:1]
('mayun',)

list和tuple互转

1
2
3
4
5
6
7
8
9
10
11
12
>>> girl1
['mahuateng', 'xiaohua', 'yanzi']
>>> boy
('mayun', 'aobama', 'liyanhong', 'mahuateng')
>>> type(gril)
<class 'list'>
>>> type(boy)
<class 'tuple'>
>>> tuple(girl1)
('mahuateng', 'xiaohua', 'yanzi')
>>> list(boy)
['mayun', 'aobama', 'liyanhong', 'mahuateng']

字典

创建字典

      每个键与值用冒号隔开(:),每对用逗号分割,整体放在花括号中({})。

1
2
3
4
5
6
7
>>> person = {"name":"adair","age":18}
>>> person
{'age': 18, 'name': 'adair'}
>>> person1 = dict({"name":"adair","age":18})
>>> person1
{'age': 18, 'name': 'adair'}
>>>

      键必须独一无二,但值则不必。
      值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
      注:type()可以查看变量类型

支持的方法

1
2
>>> dir(person)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

清除内容

      clear(self),删除字典中的所有元素

1
2
3
4
5
6
>>> person
{'age': 18, 'name': 'adair'}
>>> person.clear()
>>> person
{}
>>>

浅复制

      copy(self),返回一个字典的浅复制

1
2
3
4
5
6
>>> person = {"name":"adair","age":18}
>>> person1 = person.copy()
>>> person
{'age': 18, 'name': 'adair'}
>>> person1
{'age': 18, 'name': 'adair'}

fromkeys(S, v=None):

      S –> 字典键值列表
      v –> 可选参数, 设置键序列(seq)的值
      创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值

1
2
3
4
5
>>> seq = ('name', 'age', 'sex')
>>> dict = dict.fromkeys(seq)
>>> dict
{'age': None, 'name': None, 'sex': None}
>>>

get(self, k, d=None):

      key –> 字典中要查找的键
      default –> 如果指定键的值不存在时,返回该默认值值
      返回指定键的值,如果值不在字典中返回默认值

1
2
3
4
5
6
>>> person = {"name":"adair","age":18,"sex":"boy"}
>>> person.get("sex")
'boy'
>>> person.get("aaa")
>>> person.get("aaa","hehe")
'hehe'

has_key(self, k)

      (注:3.x已经不存在这个函数)
      用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false

1
2
3
4
5
6
7
8
9
10
>>> person = {"name": "mr.wu", 'age': 18}
# key在字典中存在就返回`True`
>>> person.has_key("name")
True
# 不存在就返回`False`
>>> person.has_key("sex")
False
#Python3.x实现方式
>>> person = {"name":"adair","age":18,"sex":"boy"}
>>> ret = "name" in person

items(self)

      以列表返回可遍历的(键, 值)元组数组

1
2
3
>>> dic={'name':'adair','age':'21','job':'IT'}
>>> dic.items()
dict_items([('age', '21'), ('name', 'adair'), ('job', 'IT')])

keys(self)

      以列表返回一个字典所有的键。

1
2
3
>>> dic={'name':'adair','age':'21','job':'IT'}
>>> dic.keys()
dict_keys(['age', 'name', 'job'])

pop(self, k, d=None)

      获取并在字典中移除,k – 要在字典中查找的键。

1
2
3
4
5
>>> dic={'name':'adair','age':'21','job':'IT'}
>>> dic.pop('job')
'IT'
>>> dic
{'age': '21', 'name': 'yaoyao'}

popitem(self)

      获取并在字典中移除

1
2
3
4
5
>>> dic={'name':'yaoyao','age':'21','job':'IT'}
>>> dic.popitem()
('age', '21')
>>> dic
{'name': 'yaoyao', 'job': 'IT'}

setdefault

      setdefault(self, k, d=None)如果key不存在,则创建,如果存在,则返回已存在的值且不修改

1
2
3
4
>>> dic={'name':'yaoyao','age':'21','job':'IT'}
>>> dic.setdefault('sex')
>>> dic
{'sex': None, 'age': '21', 'name': 'yaoyao', 'job': 'IT'}

update(self, E=None, **F)

      更新一个字典到另外一个字典

1
2
3
4
5
>>> dic={'name':'yaoyao','age':'21','job':'IT'}
>>> dic_1={'sex':'man'}
>>> dic.update(dic_1)
>>> dic
{'sex': 'man', 'age': '21', 'name': 'yaoyao', 'job': 'IT'}

values(self)

      以列表返回字典中的所有值。

1
2
3
>>> dic={'name':'yaoyao','age':'21','job':'IT'}
>>> dic.values()
dict_values(['21', 'yaoyao', 'IT'])

删除指定索引的键值对

1
2
3
4
>>> test={"a":1,"b":2,}
>>> del test["a"]
>>> test
{'b': 2}

获取全部的键值对

1
2
3
4
5
6
7
8
9
10
11
>>> user_info={"name":"adair","age":81,"gender":'M',}
>>> for k,v in user_info.items():
... print ("This is key:%s"%(k))
... print ("This is value:%s"%(v))
...
This is key:name
This is value:adair
This is key:gender
This is value:M
This is key:age
This is value:81

集合

集合(set)

      把不同的元素组成一起形成集合,是python基本的数据类型。
      集合元素(set elements):组成集合的成员
      python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.
      sets 支持 x in set, len(set),和 for x in set。
      作为一个无序的集合,set不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。

集合的创建

1
2
3
4
5
6
7
8
9
>>> se = set([11,22,33,44])
>>> print(se)
{33, 11, 44, 22}
>>> print(type(se))
<class 'set'>
或者
>>> se={'adair','jie'}
>>> se
{'jie', 'adair'}

集合的具体用法

add(添加元素)

1
2
3
4
5
>>> se
{'jie', 'adair'}
>>> se.add('123')
>>> se
{'123', 'jie', 'adair'}

clear(清空集合)

1
2
3
4
5
>>> se
{'123', 'jie', 'adair'}
>>> se.clear()
>>> se
set()

copy(浅拷贝)

1
2
3
4
>>> se_1={'adair','jie'}
>>> se_2=se_1.copy()
>>> se_2
{'jie', 'adair'}

difference差异比较

1
2
3
4
5
6
7
8
>>> se_1 = {'adair','jie','shi','shei'}
>>> se_2 = {'hao','xiang','shi','jie'}
#取出se_2中在se_1所没有的元素
>>> se_1.difference(se_2)
{'shei', 'adair'}
#取出se_1中在se_2所没有的元素
>>> se_2.difference(se_1)
{'xiang', 'hao'}

differemce_update差异更新

1
2
3
4
5
6
7
8
>>> se_1
{'shi', 'jie', 'shei', 'adair'}
>>> se_2
{'xiang', 'shi', 'jie', 'hao'}
>>> se_1.difference_update(se_2)
>>> se_1
{'shei', 'adair'}
#有点类似与去除共同的

discard移除指定元素

1
2
3
4
5
>>> se_1
{'shei', 'adair'}
>>> se_1.discard('shei')
>>> se_1
{'adair'}

intersection取交集并且建立新的集合

1
2
3
4
>>> se_1={'adair','jie','shi','boy'}
>>> se_2={'adair','jie','shi','gril'}
>>> se_1.intersection(se_2)
{'shi', 'jie', 'adair'}

intersection_update取交集并且更新原来的集合

1
2
3
4
5
6
7
>>> se_1
{'shi', 'jie', 'boy', 'adair'}
>>> se_2
{'shi', 'gril', 'jie', 'adair'}
>>> se_1.intersection_update(se_2)
>>> se_1
{'shi', 'jie', 'adair'}

isdisjoint判断没有交集,没有返回true,有返回false

1
2
3
4
5
6
7
8
9
10
11
>>> se_1={'adair','jie','shi','hao','ren'}
>>> se_2={'adair','jie','shi','huai','ren'}
>>> se_1.isdisjoint(se_2)
False
>>> se_2.isdisjoint(se_1)
False
>>> se_1={'adair','jiee'}
>>> se_2={'adairr','jiee'}
>>> se_2.isdisjoint(se_1)
True

issubset判断是否为子集

1
2
3
4
5
>>> se_1 = {'adair','jie'}
>>> se_2 = {'adair','jie','shabi'}
#判断se_1是否为se_2的子集
>>> se_1.issubset(se_2)
True

issuperset判断是否为父集

1
2
3
4
5
6
7
8
9
>>> se_1 = {'adair','jie'}
>>> se_2 = {'adair','jie','shabi'}
#判断se_1是否为se_2的父集
>>> se_1.issuperset(se_2)
False
#判断se_2是否为se_1的父集
>>> se_2.issuperset(se_1)
True
>>>

pop移除集合元素

1
2
3
>>> se_1 = {'adair','jie','sha','bi'}
>>> se_1.pop()
'sha'

remove删除指定元素集合

1
2
3
4
5
>>> se_1 = {'adair','jie','sha','bi'}
>>> se_1.remove('bi')
>>> se_1
{'sha', 'adair', 'jie'}
>>>

symmetric_difference取两个集合的差集,并建立新的元素

1
2
3
4
5
6
7
>>> se_1 = {'adair','jie','sha','bi'}
>>> se_2 = {'adair','jie','shabi'}
>>> se_1.symmetric_difference(se_2)
{'sha', 'shabi', 'bi'}
>>> b=se_1.symmetric_difference(se_2)
>>> b
{'sha', 'shabi', 'bi'}

symmetric_difference_update取两个集合的差集,更新原来的集合对象

1
2
3
4
5
>>> se_1 = {'adair','jie','sha','bi'}
>>> se_2 = {'adair','jie','shabi'}
>>> se_1.symmetric_difference_update(se_2)
>>> se_1
{'sha', 'shabi', 'bi'}

union并集

1
2
3
4
5
6
>>> se_1
{'sha', 'shabi', 'bi'}
>>> se_2
{'shabi', 'adair', 'jie'}
>>> se_1.union(se_2)
{'jie', 'sha', 'shabi', 'adair', 'bi'}

update更新集合

1
2
3
4
>>> se_1={'sha','shabi','bi'}
>>> se_1.update('adairjie')
>>> se_1
{'d', 'shabi', 'sha', 'r', 'a', 'e', 'i', 'j', 'bi'}

案例差异对比

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
old_dict = {
"#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}
new_dict = {
"#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
"#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
}
#获取old_dict元素
old = set(old_dict.keys())
print(old)
#获取new_dict元素
new = set(new_dict.keys())
print(new)
#要更新的集合元素(交集)
update_set = old.intersection(new)
print(update_set)
#获取要删除的集合元素(差集)
delete_set = old.difference(new)
print(delete_set)
#获取要添加的集合元素()
add_set = new.difference(update_set)
print(add_set)

运算符

算术运算

      以下假设a为10,b为20
Alt text

比较运算

      以下假设a为10,b为20
Alt text

赋值运算符

      以下假设a为10,b为20
Alt text

位运算

      按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:
Alt text

逻辑运算符

      Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:
Alt text

成员运算符

Alt text

身份运算符

      身份运算符用于比较两个对象的存储单元
Alt text

运算符优先级

Alt text

分享到