栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python数据类型

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python数据类型

1.1 数据类型 1.1.1 全局变量

应该尽量避免使用全局变量。不同的模块都可以自由的访问全局变量,可能会导致全局变量的不可预知性。对全局变量,如果程序员甲修改了_a的值,程序员乙同时也要使用_a,这时可能导致程序中的错误。这种错误是很难发现和更正的。

全局变量降低了函数或模块之间的通用性,不同的函数或模块都要依赖于全局变量。同样,全局变量降低了代码的可读性,阅读者可能并不知道调用的某个变量是全局变量。

1 声明法

在文件开头声明全局变量variable,

在具体函数中使用该变量时,需要事先声明 global variable,否则系统将该变量视为局部变量。CONSTANT = 0 (将全局变量大写便于识别)

2模块法(推荐)

把全局变量定义在一个单独的模块中:

#gl.py

gl_1 = 'hello'

gl_2 = 'world'

在其它模块中使用

#a.py

import gl

def hello_world()

print gl.gl_1, gl.gl_2

global与nonlocal的区别

第一,两者的功能不同。global关键字修饰变量后标识该变量是全局变量,对该变量进行修改就是修改全局变量,而nonlocal关键字修饰变量后标识该变量是上一级函数中的局部变量,如果上一级函数中不存在该局部变量,nonlocal位置会发生错误(最上层的函数使用nonlocal修饰变量必定会报错)。

第二,两者使用的范围不同。global关键字可以用在任何地方,包括最上层函数中和嵌套函数中,即使之前未定义该变量,global修饰后也可以直接使用,而nonlocal关键字只能用于嵌套函数中,并且外层函数中定义了相应的局部变量,否则会发生错误

1.1.2 数据类型转换

>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False

1.1.3 判断变量类型

判断一个变量是否是某个类型可以用isinstance()判断:

>>> isinstance(a, list)
True
>>> isinstance(b, Animal)
True
>>> isinstance(c, Dog)
True

1.1.4 字符串 1.1.4.1 判断是否为数字

str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"

#用isdigit函数判断是否数字
print(str_1.isdigit())
Ture
print(str_2.isdigit())
False
print(str_3.isdigit())
False

#用isalpha判断是否字母
print(str_1.isalpha())
False
print(str_2.isalpha())
Ture
print(str_3.isalpha())
False

#isalnum判断是否数字和字母的组合
print(str_1.isalnum())
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())
Ture

注意:如果字符串中含有除了字母或者数字之外的字符,比如空格,也会返回False

1.1.4.2 分割

re模块的split()函数可以使用多个分隔符对句子进行分割,其中不同的分隔符要用 “|” 隔开。

import re

re.split('。|!|?',text)

Out[67]: ['你好', '吃早饭了吗', '再见', '']

1.1.4.3 字符串转义

字符串内部既包含'又包含"可以用转义字符来标识,比如:'I'm "OK"!'

字符串有很多字符都需要转义可以用r''表示''内部的字符串默认不转义。

1.1.4.4 字符串前缀

字符串前加 u

例:u"我是含有中文字符组成的字符串。"

作用:后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。

字符串前加 r

例:r"nnnn” # 表示一个普通生字符串 nnnn,而不表示换行了。

作用:去掉反斜杠的转义机制。常用于正则表达式,对应着re模块。

字符串前加 b

例: response = b'Hello World!' # b' ' 表示这是一个 bytes 对象

作用:b" "前缀表示后面字符串是bytes 类型。网络编程中,服务器和浏览器只认bytes 类型数据。

bytes 和 str 的互相转换方式

str.encode('utf-8')

bytes.decode('utf-8')

1.1.4.5 多行字符串

用'''...'''的格式表示多行内容

1.1.4.6 字符编码

ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:

>>> ord('A')
65
>>> ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'文'

>>> 'u4e2du6587'
'中文'

1.1.4.7 数值字符串补0

str(1).zfill(3)

1.1.4.8 格式化

1 使用%符号进行格式

使用%符号进行字符串格式化的形式如下图所示,格式运算符%之前的部分为格式字符串,之后的部分为需要进行格式化的内容。

Python支持大量的格式字符,下表列出了比较常用的一部分。

格式字符说明
%s字符串 (采用str()的显示)
%r字符串 (采用repr()的显示)
%c单个字符
%d十进制整数
%i十进制整数
%o八进制整数
%x十六进制整数
%e指数 (基底写为e)
%E指数 (基底写为E)
%f、%F浮点数
%g指数(e)或浮点数 (根据显示长度)
%G指数(E)或浮点数 (根据显示长度)
%%字符%

使用这种方式进行字符串格式化时,要求被格式化的内容和格式字符之间必须一一对应。

>>> x = 1235

>>> so = "%o" % x

>>> so

'2323'

>>> sh = "%x" % x

>>> sh

'4d3'

>>> se = "%e" % x

>>> se

'1.235000e+03'

#等价于str()

>>> "%s" % 65

'65'

>>> "%s" % 65333

'65333'

#使用元组对字符串进行格式化,按位置进行对应

>>> '%d,%c' % (65, 65)

'65,A'

#试图将字符串转换为整数进行输出,抛出异常

>>> "%d" % "555"

TypeError: %d format: a number is required, not str

>>> '%s' % [1, 2, 3]

'[1, 2, 3]'

#可以使用str()函数将任意类型数据转换为字符串

>>> str((1, 2, 3))

'(1, 2, 3)'

>>> str([1, 2, 3])

'[1, 2, 3]'

2 使用format()方法进行字符串格式化

除了上一节介绍的字符串格式化方法之外,目前Python社区更推荐使用format()方法进行格式化,该方法非常灵活,不仅可以使用位置进行格式化,还支持使用关键参数进行格式化,更妙的是支持序列解包格式化字符串,为程序员提供了非常大的方便。

在字符串格式化方法format()中可以使用的格式主要有b(二进制格式)、c(把整数转换成Unicode字符)、d(十进制格式)、o(八进制格式)、x(小写十六进制格式)、X(大写十六进制格式)、e/E(科学计数法格式)、f/F(固定长度的浮点数格式)、%(使用固定长度浮点数显示百分数)。Python 3.6.x开始支持在数字常量的中间位置使用单个下划线作为分隔符来提高数字可读性,相应的,字符串格式化方法format()也提供了对下划线的支持。下面的代码演示了其中的部分用法:

>>> 1/3

0.3333333333333333

#保留3位小数

>>> '{0:.3f}'.format(1/3)

0.333

#格式化为百分数

>>> '{0:%}'.format(3.5)

'350.000000%'

#Python 3.6.0及更高版本支持

>>> '{0:_},{0:_x}'.format(1000000)

'1_000_000,f_4240'

#Python 3.6.0及更高版本支持

>>> '{0:_},{0:_x}'.format(10000000)

'10_000_000,98_9680'

>>> print("The number {0:,} in hex is: {0:#x}, in oct is {0:#o}".format(55))

The number 55 in hex is: 0x37, in oct is 0o67

>>> print("The number {0:,} in hex is: {0:x}, the number {1} in oct is {1:o}".format(5555, 55))

The number 5,555 in hex is: 15b3, the number 55 in oct is 67

>>> print("The number {1} in hex is: {1:#x}, the number {0} in oct is {0:#o}".format(5555, 55))

The number 55 in hex is: 0x37, the number 5555 in oct is 0o12663

>>> print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Dong", qq = "1234567", age = 38))

my name is Dong, my age is 38, and my QQ is 1234567

>>> position = (5, 8, 13)

#使用元组同时格式化多个值

>>> print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))

X:5;Y:8;Z:13

>>> weather = [("Monday", "rain"), ("Tuesday", "sunny"), ("Wednesday", "sunny"), ("Thursday", "rain"), ("Friday", "Cloudy")]

>>> formatter = "Weather of '{0[0]}' is '{0[1]}'".format

>>> for item in map(formatter, weather):

print(item)

上面最后一段代码也可以改为下面的写法:

>>> for item in weather:

print(formatter(item))

运行结果为:

Weather of 'Monday' is 'rain'

Weather of 'Tuesday' is 'sunny'

Weather of 'Wednesday' is 'sunny'

Weather of 'Thursday' is 'rain'

Weather of 'Friday' is 'Cloudy'

3 格式化的字符串常量

从Python 3.6.x开始支持一种新的字符串格式化方式,官方叫做Formatted String Literals,其含义与字符串对象的format()方法类似,但形式更加简洁。

>>> name = 'Dong'

>>> age = 39

>>> f'My name is {name}, and I am {age} years old.'

'My name is Dong, and I am 39 years old.'

>>> width = 10

>>> precision = 4

>>> value = 11/3

>>> f'result:{value:{width}.{precision}}'

'result: 3.667'

f-string大括号外如果需要显示大括号,则应输入连续两个大括号 {{ 和 }}:

name = 'Tom'

print(f'my name is {name}')
# my name is Tom

print(f'my name is {{{name}}}')
# my name is {Tom}

4 使用Template模板进行格式化

Python标准库string还提供了用于字符串格式化的模板类Template,可以用于大量信息的格式化,尤其使用于网页模板内容的替换和格式化。例如:

>>> from string import Template

#创建模板

>>> t = Template('My name is ${name}, and is ${age} yeare old.')

>>> d = {'name':'Dong', 'age':39}

#替换

>>> t.substitute(d)

'My name is Dong, and is 39 yeare old.'

>>> tt = Template('My name is $name, and is $age yeare old.')

>>> tt.substitute(d)

'My name is Dong, and is 39 yeare old.'

>>> html = '''${head}${body}'''

>>> t = Template(html)

>>> d = {'head':'test', 'body':'This is only a test.'}

>>> t.substitute(d)

'testThis is only a test.'

1.1.4.9 包含

1. in 判断,最常用。

a = 'abcdefg'
b = 'bcd'
c = 'fgh'
print(b in a)
print(c in a)

输出True和False

2.find()判断。

a = 'abcdefg'
b = 'bcd'
c = 'fgh'
print(a.find(b))
print(a.find(c))

输出1和-1。

1.1.4.10 字符出现次数

str3 = "ABCD abc is is is end"

print(str3.count("is",9,len(str3))) #就是从下标8以后开始

#(输出) 3

print(str3.count("is",10,len(str3))) #就是从下标9以后开始

#(输出) 2

1.1.4.11 替换

>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'

1.1.5 列表list 1.1.5.1 基本

列表list是一种有序的集合,可以随时添加和删除其中的元素。

比如,列出班里所有同学的名字,就可以用一个list表示:

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']

list里面的元素的数据类型也可以不同,比如:

>>> L = ['Apple', 123, True]

list元素也可以是另一个list,比如:

>>> s = ['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s)
4

要注意s只有4个元素,其中s[2]又是一个list,如果拆开写就更容易理解了:

>>> p = ['asp', 'php']
>>> s = ['python', 'java', p, 'scheme']

要拿到'php'可以写p[1]或者s[2][1],因此s可以看成是一个二维数组,类似的还有三维、四维……数组,不过很少用到。

如果一个list中一个元素也没有,就是一个空的list,它的长度为0:

>>> L = []
>>> len(L)
0

1.1.5.2 长度

用len()函数可以获得list元素的个数:

>>> len(classmates)
3

1.1.5.3 访问

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

>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range

当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1。

如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:

>>> classmates[-1]
'Tracy'

以此类推,可以获取倒数第2个、倒数第3个:

>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range

当然,倒数第4个就越界了。

1.1.5.4 增加

names = ["a","b","c","d"]

#append()仅支持添加一个元素

names.append("e")

#extend()增加一个列表

names.extend(["e","f"])

#insert()根据索引添加元素

names.insert(1,"t")

#直接使用"+"号合并列表

names+["e","f"]

#使用切片

aList[len(aList):len(aList)] = bList

1.1.5.5 删除

1 #删除remove()删除指定值的元素

2 x = [1,2,3,4,5]

3 x.remove(2)

4 print("--------删除2----------")

5 print(x)

6 names=["Alice","Linda","Bob"]

7 names.remove("Bob")

8 print("--------删除BOb----------")

9 print(names)

10

11 #del 根据索引删除元素

12 numbers = [6,7,8,9,10,11]

13 del numbers[1]

14 print("--------删除索引1----------")

15 print(numbers)

16

17 # pop()根据索引获取并删除元素

18 numbers1 = [6,7,8,9,10,11]

19 numbers1.pop(1)

20 print("--------删除索引1----------")

21 print(numbers1)

22 numbers1.pop()

23 print("--------删除最后一个元素----")

24 print(numbers1)

输出结果

--------删除2----------

[1, 3, 4, 5]

--------删除BOb----------

['Alice', 'Linda']

--------删除索引1----------

[6, 8, 9, 10, 11]

--------删除索引1----------

[6, 8, 9, 10, 11]

--------删除最后一个元素----

[6, 8, 9, 10]

直接先给出输出与预期不同的代码

In[28]: a = [1,2,3,4,5,6]
In[29]: for i in a:
...: a.remove(i)
...:
In[30]: a
Out[30]: [2, 4, 6]

在上述for循环中,假设我们删除了index=2的值,原本index=3及之后的值会向前补位,所以在循环中就跳过了原index=3的变量

同理,使用list.pop()函数删除指定元素的时候,也会出现上述情况,如:

In[33]: a = [1,2,3,4,5,6]
In[34]: for index, value in enumerate(a):
...: a.pop(index)
...:
In[35]: a
Out[35]: [2, 4, 6]

如果我们想循环删除列表中的元素,较简单的可用方法有:用一个临时列表保存待删除的元素,在for循环临时列表来删除老列表中的元素;或者直接用剩余元素列表覆盖原列表

搞这么复杂,倒序循环之后,删除就不会有下标错乱的问题了

  1. for i in a[::-1]:
  2. if not a:
  3. a.remove(i)
1.1.5.6 修改

要把某个元素替换成别的元素,可以直接赋值给对应的索引位置:

>>> classmates[1] = 'Sarah'
>>> classmates
['Michael', 'Sarah', 'Tracy']

1 #分片赋值

2 str1 = ["a","b","c"]

3 # 替换索引>=2

4 str1[2:] = list("de")

5 print("替换索引>=2结果 :",str1)

6 #删除索引2

7 str1[2:2] = "f"

8 print("删除索引2结果 :",str1)

9 #赋值且替换索引2-3

10 str1[2:4] = ["g","h","i"]

11 print("赋值且替换索引2-3结果 :",str1)

12 #删除元素

13 str1[:] = []

14 print("删除所有结果 :",str1)

输出结果

替换索引>=2结果 : ['a', 'b', 'd', 'e']

删除索引2结果 : ['a', 'b', 'f', 'd', 'e']

赋值且替换索引2-3结果 : ['a', 'b', 'g', 'h', 'i', 'e']

删除所有结果 : []

1.1.5.7 生成定长数据

a = [1] * 10 定义一个长度为10的list

1.1.5.8 删除重复数据

使用set()

list1=sorted(set(list0),key=list0.index) # sorted output
print( list1)

1.1.5.9 元素是否存在

1 #搜索元素

2 names1=["Alice","Linda","Bob"]

3 if "Alice" in names1:

4 print(True)

5 else:

6 print(False)

输出结果

True

1.1.5.10 搜索元素索引值

1 #index()元素索引值,这种方法仅仅能获取都第一个匹配的value的下标

2 str1 = ["a","b","c"]

3 print(str1.index("a"))

输出结果

0

1.1.5.11 统计元素出现次数

1 #count()统计某元素出现次数

2 number1 = [1,2,1,3,4]

3 print(number1.count(1))

输出结果

2

1.1.5.12 反向存放

1 #reverse将列表中的元素反向存放,返回值为null

2 number1 = [1,2,1,3,4]

3 number1.reverse();

4 print(number1)

输出结果

[4, 3, 1, 2, 1]

1.1.5.13 排序

1 #sort()方法:对元素进行排序,返回值为null

2 number1 = [1,2,1,3,4]

3 number1.sort()

4 print(number1)

5 #sorted()返回值为排序后的数组

6 number2 = [1,2,1,3,4]

7 y=sorted(number2);

8 print(y)

9 print(number2)

输出结果

[1, 1, 2, 3, 4]

[1, 1, 2, 3, 4]

[1, 2, 1, 3, 4]

Python内置的sorted()函数就可以对list进行排序:

>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]

sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序:

>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

给sorted传入key函数,即可实现忽略大小写的排序:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

1.1.5.14 过滤

Python内建的filter()函数用于过滤序列。

在一个list中,删掉偶数,只保留奇数,可以这么写:

def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]

把一个序列中的空字符串删掉,可以这么写:

def not_empty(s):
return s and s.strip()

list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']

filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。

1.1.6 元组tuple

元组tuple和list非常类似,但是tuple一旦初始化就不能修改,比如同样是列出同学的名字:

>>> classmates = ('Michael', 'Bob', 'Tracy')

现在,classmates这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。

不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。

tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,比如:

>>> t = (1, 2)
>>> t
(1, 2)

如果要定义一个空的tuple,可以写成():

>>> t = ()
>>> t
()

但是,要定义一个只有1个元素的tuple,如果你这么定义:

>>> t = (1)
>>> t
1

定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。

所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:

>>> t = (1,)
>>> t
(1,)

Python在显示只有1个元素的tuple时,也会加一个逗号,,以免你误解成数学计算意义上的括号。

最后来看一个“可变的”tuple:

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

这个tuple定义的时候有3个元素,分别是'a','b'和一个list。不是说tuple一旦定义后就不可变了吗?怎么后来又变了?

别急,我们先看看定义的时候tuple包含的3个元素:

当我们把list的元素'A'和'B'修改为'X'和'Y'后,tuple变为:

表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!

理解了“指向不变”后,要创建一个内容也不变的tuple怎么做?那就必须保证tuple的每一个元素本身也不能变。

1.1.7 字典dict 1.1.7.1 基本

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

和list比较,dict有以下几个特点:

1. 查找和插入的速度极快,不会随着key的增加而变慢;

2. 需要占用大量的内存,内存浪费多。

而list相反:

1. 查找和插入的时间随着元素的增加而增加;

2. 占用空间小,浪费内存很少。

所以,dict是用空间来换取时间的一种方法。

1.1.7.2 判断存在

判断key是否存在:

一是通过in判断key是否存在:

>>> 'Thomas' in d
False

二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:

>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1

1.1.7.3 删除

删除key:

>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}

1.1.7.4 查询

字典的 keys() 方法返回一个展现键集合的键视图对象,该对象支持集合操作,比如集合并、交、差运算。 所以,可以直接对字典的键执行普通的集合操作,而不用先将它们转换成一个 set。

字典的 values() 方法返回结果,并不支持集合操作,因为值视图不能保证所有的值互不相同,这样会导致某些集合操作出现问题,可以先将值集合转换成 set,然后再执行集合运算。

字典的 items() 方法返回一个包含 (键,值) 对的元素视图对象,该对象同样也支持集合操作。

1.1.7.5 删除

Python字典的clear()方法(删除字典内所有元素)

dict = {'name': '我的博客地址', 'alexa': 10000, 'url': 'http://blog.csdn.net/uuihoo/'}

dict.clear(); # 清空词典所有条目

Python字典的pop()方法(删除字典给定键 key 所对应的值,返回值为被删除的值)

site= {'name': '我的博客地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'}

pop_obj=site.pop('name') # 删除要删除的键值对,如{'name':'我的博客地址'}这个键值对

print pop_obj # 输出 :我的博客地址

Python字典的popitem()方法(随机返回并删除字典中的一对键和值)

site= {'name': '我的博客地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'}

pop_obj=site.popitem() # 随机返回并删除一个键值对

print pop_obj # 输出结果可能是{'url','http://blog.csdn.net/uuihoo/'}

del 全局方法(能删单一的元素也能清空字典,清空只需一项操作)

site= {'name': '我的博客地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'}

del site['name'] # 删除键是'name'的条目

del site # 清空字典所有条目

1.1.8 集合set 1.1.8.1 基本

集合(set)是一个无序的不重复元素序列。

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

创建格式:

parame = {value01,value02,...}

创建一个set,需要提供一个list作为输入集合:

>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}

注意,传入的参数[1, 2, 3]是一个list,而显示的{1, 2, 3}只是告诉你这个set内部有1,2,3这3个元素,显示的顺序也不表示set是有序的。。

重复元素在set中自动被过滤:

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

1.1.8.2 增加

通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:

>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

1.1.8.3 删除

通过remove(key)方法可以删除元素:

>>> s.remove(4)
>>> s
{1, 2, 3}

1.1.8.4 集合运算

set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

1.1.9 字符串、字典、列表转化 1.1.9.1 字符串和列表

字符串转列表

str1 = "12345"

list1 = list(str1)

print list1

str2 = "123 sjhid dhi"

list2 = str2.split() #or list2 = str2.split(" ")

print list2

str3 = "http://www.google.com"

list3 = str3.split(".")

print list3

输出为:

['1', '2', '3', '4', '5']

['123', 'sjhid', 'dhi']

['www', 'google', 'com']

列表转字符串

str4 = "".join(list3)

print str4

str5 = ".".join(list3)

print str5

str6 = " ".join(list3)

print str6

输出为:

wwwgooglecom

http://www.google.com

www google com

1.1.9.2 字符串和字典

字符串转换为字典:

str_test = "{'a': 1, 'b': 2}"

dict_test = eval(str_test)

print dict_test

字典转换为字符串:

dict_test = {'a': 1, 'b': 2}

str_test = str(dict)

print str_test

1.1.9.3 列表和字典

列表转字典

1、构建字典的 2 个列表相同

>>> a = [1,2,3,4]

>>> b = ['ab','ac','ad']

>>> dict(zip(a,b))

{1: 'ab', 2: 'ac', 3: 'ad'}

>>>

2、构建字典的 2 个列表不同(key比value多)

>>> a = [1,2,3,4]

>>> c = ['aa','ss']

>>> dict(zip(a,c))

{1: 'aa', 2: 'ss'}

>>>

3、构建字典的 2 个列表不同(key比value少)

>>> a = [1,2,3,4]

>>> d = ['fa','fb','fc','fd','fe']

>>> dict(zip(a,d))

{1: 'fa', 2: 'fb', 3: 'fc', 4: 'fd'}

1.1.10 可遍历对象转索引序列

描述

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。

返回值

返回 enumerate(枚举) 对象。

实例

以下展示了使用 enumerate() 方法的实例:

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']

>>>list(enumerate(seasons))

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>>list(enumerate(seasons, start=1)) # 小标从 1 开始

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

1.1.11 枚举

enum模块是系统内置模块,可以直接使用import导入,但是在导入的时候,不建议使用import enum将enum模块中的所有数据都导入,一般使用的最多的就是enum模块中的Enum、IntEnum、unique这几项

# 导入枚举类

from enum import Enum

# 继承枚举类

class color(Enum):

YELLOW = 1

BEOWN = 1

# 注意BROWN的值和YELLOW的值相同,这是允许的,此时的BROWN相当于YELLOW的别名

RED = 2

GREEN = 3

PINK = 4

class color2(Enum):

YELLOW = 1

RED = 2

GREEN = 3

PINK = 4

使用自己定义的枚举类:

print(color.YELLOW) # color.YELLOW

print(type(color.YELLOW)) #

print(color.YELLOW.value) # 1

print(type(color.YELLOW.value)) #

print(color.YELLOW == 1) # False

print(color.YELLOW.value == 1) # True

print(color.YELLOW == color.YELLOW) # True

print(color.YELLOW == color2.YELLOW) # False

print(color.YELLOW is color2.YELLOW) # False

print(color.YELLOW is color.YELLOW) # True

print(color(1)) # color.YELLOW

print(type(color(1))) #

注意事项如下:

1、枚举类不能用来实例化对象

2、访问枚举类中的某一项,直接使用类名访问加上要访问的项即可,比如 color.YELLOW

3、枚举类里面定义的Key = Value,在类外部不能修改Value值,也就是说下面这个做法是错误的:color.YELLOW = 2 # Wrong, can't reassign member

4、枚举项可以用来比较,使用==,或者is

5、导入Enum之后,一个枚举类中的Key和Value,Key不能相同,Value可以相,但是Value相同的各项Key都会当做别名,

6、如果要枚举类中的Value只能是整型数字,那么,可以导入IntEnum,然后继承IntEnum即可,注意,此时,如果value为字符串的数字,也不会报错:from enum import IntEnum

7、如果要枚举类中的key也不能相同,那么在导入Enum的同时,需要导入unique函数from enum import Enum, unique

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846516.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号