Python基础 - 常用内置对象
数字、字符串、字节串、列表、元组、字典、集合、布尔型、空类型、异常、文件、可迭代对象、编程单元def、class、module
常量与变量
x = 3
type(x) # 查看变量类型
int
type(x) == 'int'
False
isinstance(x, int)
True
isinstance(obj, class_or_tuple,/)
Return whether an object is an instance of a class or of a subclass therof.
x = 'hello world.'
x1_id = id(x)
x = [1, 2, 3]
x2_id = id(x)
print(x)
#type(x1_id)
# 格式化输出尚未解决
print(x1_id, x2_id)
[1, 2, 3]
189910967472 189923805064
print(value1,value2..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream(流), or to sys.stdout(系统标准输出) by default(默认情况下)
Optional keyword arguments:
- sep: string inserted between values(值之间插入的字符串), default a space.
- end: string append after the last value, default a newline(换行符\n)
- file: a file-like object(stream)(类文件对象), defaults to the current sys.stdout.
- fulsh: whether to forcibly flush(强制冲掉) the stream.
Signature: id(obj,/)
Dostring: Return the identity(地址) of an object.
This is guaranteed(保证) to be unique among simultaneously(同时地) existing objects.(Cpython uses the object's memory adress(内存地址)
Python 中的变量并不直接存储值,而是存储了变量的地址或者引用(类似C的指针),这是变量类型可以随意改变的原因。
数字
999 ** 99 # ** 是幂,等价于pow()
905697844958667709741956562802753100901389806139609538815019658231017504097064752403846139892968390554024852396172082441213697329994395340901282449426848216146865935961454742677324005498146550510264840271813301125214581059267630055862747172378231729576039278689152963667155086263379780844149098999
0.3 + 0.2 # 实数相加
0.5
0.4 - 0.1 # 这存在精度的问题
0.30000000000000004
0.4 - 0.1 == 0.3 # 尽量避免直接比较两个实数是否相等的情景
False
abs(0.4 - 0.1 - 0.3) < 1e-6 # 'le-6'表示10的-6次方
True
abs(x,/)
Return the absolute(绝对值)of the argument.
x = 3 + 4j # j表示复数虚部
y = 5 + 6j
print(x + y)
print(x * y)
(8+10j)
(-9+38j)
print(abs(x)) # abs()可以用来计算复数的模
5.0
print(x.real) # 实部
print(x.imag) # 虚部
3.0
4.0
# x = x.conjugate # 不加括号()返回方法对象
#type(x)
builtin_function_or_method
print(x.conjugate()) # 共轭复数
(3-4j)
complex.conjugate()
Return the complex conjugate of its argument. eg. (3-4j).conjugate() == 3+4j.
字符串与字节串
#哈哈 = 123 # Python 3.x 全面支持中文、英文作文一个字符对待
#print(哈哈)
世界上最帅的人是谁 = '是杰哥'
print(世界上最帅的人是谁)
是杰哥
x = 'hello,world.' # 单引号
y = "Python is a great language." # 双引号
z = '''Cj said, "Let's learn Python together."''' # 三引号及界定符间的嵌套
print(x)
print(y)
print(z)
hello,world.
Python is a great language.
Cj said, "Let's learn Python together."
x = 'good' + 'morning' # 连接字符串
print(x)
goodmorning
x = 'good'
x += ' moring'
print(x)
good moring
对str类型的字符串调用encode() 方法进行编码 得到bytes字节串;
对bytes 字节串调用decode() 方法并指定正确的编码格式(解码)得到str字符串。
type('hello, world') # 默认我str
str
type(b'hello,world')
bytes
'Hello, world'.encode('utf-8') # 使用UTF-8编码
b'Hello, world'
'Hello,world'.encode('gbk') # 使用gbk编码
b'Hello,world'
myName = '陈杰'
myName.encode('utf-8') # 对中文进行编码
b'\xe9\x99\x88\xe6\x9d\xb0'
str 有编码方法,却没有解码方法,奇怪
myName.decode('gbk')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-02e2fe96b205> in <module>()
----> 1 myName.decode('gbk')
AttributeError: 'str' object has no attribute 'decode'
_.decode('utf-8') # 下划线表示最后一次正确输出的结果
'陈杰'
'陈杰油格哥'.encode('gbk')
b'\xb3\xc2\xbd\xdc\xd3\xcd\xb8\xf1\xb8\xe7'
_.decode('gbk') # 对bytes字节串进行解码
'陈杰油格哥'
_.decode(encoding='utf8',errors='strict')
Decode the bytes using the codec registered (注册的解码器)for encoding.
列表、元组、字典、集合
x_list = [1,2,3] # create a list object
x_tuple = (1,3,2) # create a tuple object
x_dict = {'a' : 666, 'b' : 888, 'c': 'NB'} # create a dict object.
x_set = {1,2,'c'} # crate a set object.
print(x_list[1]) # Using the subscripts to access element of a specified locationg.
2
print(x_tuple[0]) # Tuples also support the use of serial numbers(index) as subscripts.
1
print(x_dict['a']) # the subscript of the dictionary object is the key.
666
print(x_set[0]) # 'set' object does not support indexing.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-6871ff8416c2> in <module>()
----> 1 print(x_set[0])
TypeError: 'set' object does not support indexing
print(3 in x_set) # Whether a member is in the 'set' object.
print(2 in x_set)
False
True
除了这里的list;tuple; dict;set外,还有string也支持;还有可迭代对象 range; map; zip; filter; enumerate; reversed等(迭代对象可理解为表示数据流的对象,每次返回一个数据) 与序列sequence 不同在于其具有惰性求值 的特点,仅需调用时才给出新才元素,减少了对内存的占用。
运算符与表达式
对象 = 数据 + 行为
算术运算符
'+ - * / // % **' == < <= > >= != not and or in is | ^ & << >> ~ & | ^ @
+’ 除了用于算术‘+’,还可以用于列表、元组、字符串的连接
[1,2,3] + [3,4,5,'abc'] # Connect two lists.
[1, 2, 3, 3, 4, 5, 'abc']
(1,2,'c') + (5,) # Connect two tuples
(1, 2, 'c', 5)
'chenjie' + 'youge' # Connect two strings.
'chenjieyouge'
'chenjie' + 666 # Connection between different types of objecets is not supported.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-380095099055> in <module>()
----> 1 'chenjie' + 666
TypeError: must be str, not int
True + 1 # Python internally(内部地)treats(处理)True as 1
2
False + 1 # Python internally treats False as 0
1
' * ' 不仅表示乘,还可用于列表、元组、字符串的元素重复,生成新对象。但字典、集合不能,因为这俩元素不能重复。
False * 3
0
True * 3
3
[1,2,3,3,'abc'] * 3
[1, 2, 3, 3, 'abc', 1, 2, 3, 3, 'abc', 1, 2, 3, 3, 'abc']
(1,'b',2,2) * 3
(1, 'b', 2, 2, 1, 'b', 2, 2, 1, 'b', 2, 2)
'chenjieNB' * 3
'chenjieNBchenjieNBchenjieNB'
' / ' 和 ' // ' 表示算术除和整商floor division
3 / 2
1.5
10 / 3
3.3333333333333335
15 // 4 # floor 3.75~ 3(向下取整)
3
15 // 4.0
3.0
3.75 * 4
15.0
-15 // 4 # 向下取整,-3.75往下,即忘数轴的左边取邻近的整数
-4
' % ' 求余和字符串格式化
10 % 3 # Remainder
1
123.45 % 3.3
1.3500000000000094
'string: %c, int: %d'% (65,65) # Format 65 as a character and an integer
'string: A, int: 65'
'float: %f, string: %s, %r' % (65,66,'nnn') # 为啥不能结合print()呢?
"float: 65.000000, string: 66, 'nnn'"
' ** ' 表示幂,等价于内置函数pow(x, y, z=None, /)
2 ** 10 # 2 to the power of 10, equivalent to(等价于)pow(2, 10)
1024
pow(x, y, z=None, /)
Equivalent to x ** y(with two arguments) or x ** y % z (with three arguments).
Some types, such as ints, are able to use a more efficient algorithm(高效算法)when invoked(调用)using the three argument form.
pow(2, 3, 6) # Equivalent to (2 ** 3) % 6, the result is 2
2
9 ** 0.5 # square root of 9
3.0
(-9) ** 0.5 # sqrt(-0.9)
(1.8369701987210297e-16+3j)
关系运算符
< <= > >= == !=
1 < 3 < 5 # Equivalent to (1<3) and (3<5)
True
3<5>2
True
1<2>3
False
import math
3>2<math.sqrt(9)
True
'hello' > 'world' # Compare the size of strings
False
[1,2,3,3] < [1,2,3,4] # Compare the size of lists
True
'hello' < 3 # String and numbers can not be compared
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-76-55556ec954d3> in <module>()
----> 1 'hello' < 3
TypeError: '<' not supported between instances of 'str' and 'int'
{1,2,3,'a'} < {3,2,'w','a',1} # Test if it is a subset
True
{1,2,3} == {1,3,'%dd'}
False
3 != 4
True
成员测试in 与同一性测试is
3 in [1,3,2] # Test if 3 exists in lists [1,3,2]
True
x = range(5)
type(x)
range
list(range(5)) # Equivalent to list(range(0,5,1))
[0, 1, 2, 3, 4]
range(start = 0, stop, step)
Return an object that produce a sequence of integers from start(inclusive包含)to stop(exclusive不包含)by step.
range(i, j) produce i,i+1, i+2....,j-2, j-1.
start defaults to 0, and stop is omitted!(被省略) range(4) produces 0,1,2,3
These are exactly(正确地)the vaild indices(有效索引) for a list of 4 elements.
When step is given, it specifies(指定)the increment(or decremnte).
5 in range(1,10,1)
True
'abc' in 'abcdefg' # String test
True
for i in (5,2,0,'you'): # Loop,member traversal(成员遍历)
print(i)
5
2
0
you
for i in (5,2,0,'you'): # Loop,member traversal(成员遍历)
print(i,end='\t')
5 2 0 you
for i in (5,2,0,'you'): # Loop,member traversal(成员遍历)
print(i,end=' ')
5 2 0 you
Identity comparison ** is** 用来测试两个对象是否为同一个(True;False).若两个对象为同一个,两者具有相同的内存地址
'chenjie' is 'chenjie'
True
x = [666,666,666]
print(id(x))
print(id(x[0]))
print(id(x[-1]))
390655677128
390653462992
390653462992
x[0] is x[1] # The same value has only one copy in memory
True
x = [1,2,3,'d']
y = [1,2,3,'d']
x is y # The x and y created by the above form are not the same list object
False
x[0] is y[0]
True
x.append(4) # Dose not affect the value of y
print(x)
print(y)
[1, 2, 3, 'd', 4]
[1, 2, 3, 'd']
位运算与集合运算
十进制转二进制
方法为:十进制数除2取余法,即十进制数除2,余数为权位上的数,得到的商值继续除2,依此步骤继续向下运算直到商为0为止,让后倒过来写余数。
eg.150不断除以2取余,分别为:
# def toBin(number):
# '''Convert a decimal(十进制) integer to binary'''
# remaind_list = []
# while True:
# quotient = number / 2
# remainder = number % 2
# remaind_list.append(remainder)
# if quotient == 0:
# break
# return remaind_list.reverse()
bin(2)
'0b10'
map(str [1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-343975d5b11c> in <module>()
----> 1 map(str [1,2,3])
TypeError: 'type' object is not subscriptable
位运算暂时不会先留着
举例几个集合运算
{1,2,3,3,4} # ‘set’object automatically remove duplicate elements
{1, 2, 3, 4}
{1,2,3,4} & {3,4,5,6} # Intersection
{3, 4}
{1,2,3,4} | {3,4,5,6} # Union
{1, 2, 3, 4, 5, 6}
{1,2,3,4} ^ {3,4,5,6} # Symmetric difference set(对称差集)
{1, 2, 5, 6}
{1,2,3,4} - {3,4,5,6} # Difference set
{1, 2}
逻辑运算符
not and or
4 > 5 and a > 3 # Note that the variable 'a' is not difined at this time
False
4 > 5 or a > 3
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-b2e756accdfc> in <module>()
----> 1 4 > 5 or a > 3
NameError: name 'a' is not defined
3 > 1 or a > 3 # When the value is True, you don't need the following expression
True
3 and 5 # The value of the last evaluated expression as the value of the entire expression
5
3 and 5 > 2
True
6 not in [1,3,4,6]
False
6 is not 5
True
not 0
True
Python 关键字
True False None in is
not and or
if elif else break continue
try except finally assert raise
import from as
def pass return lambda class
for while
global nonlocal del yield
常用内置函数
总览
类型转换与类型判断
bin();oct();hex();int();float(); complex()...
ord();chr()
bin(150) # Turn numbers into binary string
'0b10010110'
- bin(number, /)
Return the binary representation(表示) ot an integer(decimal)
bin?? equivalent to "shift + tab*4 "
oct(666) # Convert number to octal(八进制)string
'0o1232'
- oct(number,/)
Return the octal representation of an integer.
hex(666) # Convert number to hexadecimal string
'0x29a'
- hex(number,/)
Return the hexadecimal representation of an integer.
int(- 9.99)
-9
bin(666)
'0b1010011010'
int('0b1010011010', 2)
666
- int(self, /, *args, **kwargs)
int(x=0) -- integer
int(x, base=10) --integer
Convert a number or string(数字串) to an integer, or return 0 if no arguments are given.
If x is a number, return x.int().For float point number(浮点数),this truncates(截取)towards zero.(去掉小数点取整)
If x is not a number or if base is given, then x must be a string,bytes, or bytearray instance representing an intege literal in the given base.(当base确定,x必须是bytes或bytearray实例,以表示文中的整数串)
The base defaults to 10.Valid bases are() and 2-36.
Base 0 means to interpret(说明)the base from the string as an integer literal.
int('0x378', 16)
888
int('22b', 16)
555
int(bin(54321), 2)
54321
int('ob111') # Non - decimal string, the second parameter must be specified
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-44-a8331f7521f1> in <module>()
----> 1 int('ob111')
ValueError: invalid literal for int() with base 10: 'ob111'
float(666)
666.0
- float(self, /, *args, **kargs)
float(x) -- floating point number(将其他类型转为浮点型)
Convert a strint or a number to a float point number, if possible.
float('3.5') # Convert a numric strng to a real number
3.5
float('inf') # infinity无穷大
inf
complex(3)
(3+0j)
- complex(real,image)
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + image1j) where image defaults to 0.
complex(3,4)
(3+4j)
complex('inf')
(inf+0j)
ord() 与chr() 一对功能相反函数,前者是返回其Unicode码
ord('a')
97
chr(97)
'a'
ord('陈')
38472
ord('杰')
26480
chr(38472)
'陈'
chr(666)
'ʚ'
x = 'xxx' # 等同于遍历join(str),将"xxx",加到每次遍历元素的后面
x.join('dj')
'dxxxj'
" s".join('[1,2,3,5]')
'[ s1 s, s2 s, s3 s, s5 s]'
map(str, '123')
<map at 0x5f596e91d0>
map(str, [1,2,3])
<map object at 0x0000005F596F2EF0>
''.join(map(str,([1,4,5]))) # 将列表元素组合为字符串
'145'
str([1,2,3])
'[1, 2, 3]'
str({'a':3, 3:1})
"{'a': 3, 3: 1}"
eval('(2,4,5,6,3)') # (计算字符串表达式的值)看起来它像什么,它就认为是什么,很神奇,但很多公司不让用,容易被黑客
(2, 4, 5, 6, 3)
Signature: eval(source, globals=None, locals=None, /)
Docstring:
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
Type: builtin_function_or_method)
eval("{2:5,4:5}") # eaval() 到底怎么使用,我还要进一步探索
{2: 5, 4: 5}
x = 7
eval("3 * x")
21
"1 + 1"
'1 + 1'
eval('1 + 1')
2
eval("[i for i in range(5)]")
[0, 1, 2, 3, 4]
eval("'Hello world'")
'Hello world'
list(); tuple(); ditc(); set(); frozenset()
list(range(5))
[0, 1, 2, 3, 4]
tuple(_) # 下划线表示上次运行成功的结果值
(0, 1, 2, 3, 4)
type(_)
tuple
dict(zip('abcd',[1,2,3,4,5,6])) # zip拉链函数,拉完匹配的,余下就不管了
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
set([1,1,3,2,4,5,7,'b', (1,3,4)]) # set()最重要的功能是去重元素,不能弄字典不过
{(1, 3, 4), 1, 2, 3, 4, 5, 7, 'b'}
_.add(666)
print(_)
{1, 2, 3, 4, 5, 7, 'b', (1, 3, 4), 666}
# 创建不可变集合
frozenset({1,2,4,5,3,5,5,})
frozenset({1, 2, 3, 4, 5})
_.add(666)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-34-e276597d9d86> in <module>()
----> 1 _.add(666)
AttributeError: 'frozenset' object has no attribute 'add'
type();isinstance() 判断数据类型
type(3)
int
type([3])
list
type({3})
set
type((3,)) in (list, int, dict)
False
isinstance(3, int)
True
isinstance('s', str)
True
isinstance([1], (tuple, list, dict, set))
True
最值与求和
max(); min(); sum()
import random
a = [random.randint(1,100) for i in range(10)] # 产生1-100间的整数10个,组成列表
print(max(a), min(a), sum(a))
print(sum(a) / len(a)) # 平均值
88 9 421
42.1
max(iterable, default=obj, key=func)
Docstring:
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
max([1,3,4,5,1,5,77,6,66,3])
77
from random import randint
lst = [[randint(1,50) for i in range(5)] for j in range(30)]
lst
[[39, 10, 23, 5, 32],
[15, 14, 28, 29, 31],
[23, 45, 25, 36, 47],
[19, 26, 38, 43, 29],
[29, 26, 10, 48, 28],
[18, 40, 8, 9, 29],
[43, 38, 44, 1, 7],
[18, 37, 24, 10, 47],
[28, 15, 46, 21, 7],
[11, 31, 8, 17, 7],
[35, 3, 39, 48, 7],
[9, 31, 44, 29, 39],
[31, 44, 18, 41, 34],
[15, 12, 44, 11, 40],
[37, 32, 33, 7, 23],
[8, 26, 12, 39, 44],
[7, 25, 14, 33, 23],
[6, 24, 9, 37, 20],
[9, 45, 12, 44, 31],
[26, 9, 18, 5, 43],
[9, 7, 25, 25, 38],
[33, 31, 45, 20, 39],
[37, 23, 26, 32, 1],
[50, 1, 5, 8, 8],
[28, 1, 19, 38, 37],
[35, 15, 8, 7, 22],
[42, 2, 28, 13, 24],
[14, 3, 35, 25, 30],
[23, 10, 37, 30, 6],
[36, 24, 24, 25, 49]]
max(lst, key=sum) # 返回元素之和最大的列表
[23, 45, 25, 36, 47]
max(lst, key=lambda x:x[1]) # 返回子列表中第2个元素最大的子列表, 即45所在的那个列表
[23, 45, 25, 36, 47]
sum(range(10))
45
sum(range(1,11),5) # start == 5, 等价于 5 + sum(range(1,11))
60
sum([[1,2],[3],[4]],[]) # 列表的 连接 占用空间很大,慎用
[1, 2, 3, 4]
sum(2**i for i in range(200)) # 等比数列前n项的和 1+2+4+8+16+。。。
1606938044258990275541962092341162602522202993782792835301375
int('1' * 200, 2) # 等价于上行代码,但效率高很多
1606938044258990275541962092341162602522202993782792835301375
sum(range(101)) # 101人开会,互相握手次数,不重复握手
5050
101 * 100/2 # 数列求和,算法上个高效
5050.0
基本输入与输出
input(); print()
x = input("Please input: ")
Please input: 12345
x
'12345'
type(x)
str
eval(x) # 对字符串求值,或类型转换(执行一个字符串表达式,并返回表达式的值) 它认为看起来像什么,就认为是什么
12345
print(value1,value2,...,sep = '', end="\n", file=sys.stdout, flush=False)
- sep 前面可以输出多个值
- sep 指定数据间的分隔符,默认为空格
- end 指定下次print怎么显示,默认是"\n", end="\t"常用,比如打印 9x9乘法表等
- file指定输出位置,默认为标准控制台,也可以重定向输出到文件
print(1,2,4,5,'abc')
1 2 4 5 abc
print(1,2,3,'bac', sep='\t\t') # 值间的分隔符
1 2 3 bac
for i in range(5):
print(i, end=' ') # 每个输出之间不换行
0 1 2 3 4
with open("test.txt", 'a+') as fp:
print("hello world ", file = fp) # 重定向,将内容输到文件中,等同于 fp.write(), 感觉用print()挺好,还能自动换行
fp.write("i love Python")
排序与逆序
sorted(); reversed()
sorted(iterable, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
x = list(range(11))
x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random
random.shuffle(x) # 随机打乱顺序
x
[1, 9, 0, 5, 10, 3, 4, 2, 7, 6, 8]
sorted(x) # 默认升序
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sorted(x, reverse=True)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# 转成字符串,并按字符串长度降序排列
sorted(x, key = lambda item: len(str(item)), reverse=True)
[10, 1, 9, 0, 5, 3, 4, 2, 7, 6, 8]
sorted(x, key=str)
[0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
x # 不改变原字符串(不可变对象)
[1, 9, 0, 5, 10, 3, 4, 2, 7, 6, 8]
枚举
enumerate()
enumerate(self)
Docstring:
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
enumerate('abcde')
<enumerate at 0xa555890af8>
for i in enumerate(range(5)):
print(i)
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
list(enumerate('abcde'))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
list(enumerate(['Python', 'Create']))
[(0, 'Python'), (1, 'Create')]
# 枚举字典中的元素:keys/values/items
list(enumerate({'a':99, 'b':88, 'c':66}.items()))
[(0, ('a', 99)), (1, ('b', 88)), (2, ('c', 66))]
list(enumerate({'a':99, 'b':88, 'c':66}.keys())) # 枚举字典中的键
[(0, 'a'), (1, 'b'), (2, 'c')]
list(enumerate({'a':99, 'b':88, 'c':66}.values())) # 枚举字典中的值
[(0, 99), (1, 88), (2, 66)]
# enumerate()还支持一个start参数,指定枚举时的索引起始值
for item in enumerate(range(5), 6):
print(item, end=' ')
(6, 0) (7, 1) (8, 2) (9, 3) (10, 4)
高阶函数
map(); reduce(); filter()
map(func, iterable) 接收一个函数和一个可迭代对象,并将函数作用于(映射)可迭代对象的每一个元素
from functools import reduce # Python3,将reduce()放在了标准库 functools中了
x = list(range(5))
x
[0, 1, 2, 3, 4]
list(map(str, x)) # map() 不会对原序列或迭代器对象做任何修改
['0', '1', '2', '3', '4']
x
[0, 1, 2, 3, 4]
list(map(x**2, range(10)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-53-b7458c45ed40> in <module>()
----> 1 list(map(x**2, range(10)))
TypeError: 'int' object is not callable
def add5(x):
return x + 5
list(map(add5, range(10))) # 把add5() 映射到,后面序列的每个元素(element作为add5的参数)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
list(map(lambda x, y: x + y, range(1,6), range(6,11))) # 将双参数映射到两个序列上
[7, 9, 11, 13, 15]
import random
x = random.randint(1,1e30) # 生成指定范围内的随机整数
x
print(list(map(int, str(x))), end=' ') # 提取每位上的数字
[3, 4, 3, 2, 4, 2, 6, 5, 4, 3, 9, 9, 1, 4, 2, 8, 4, 3, 9, 9, 6, 9, 8, 0, 2, 5, 8, 4, 0]
# 补:之前的水仙花案例
for num in range(100, 1000):
a,b,c = map(int, str(num)) # 截取出一个整数的每个位上的数字,如:123,分别取出:1,2,3
if a**3 + b**3 + c**3 == num:
print(num, end=" ")
153 370 371 407
reduce(func, sequence)接收2个参数的函数,以迭代累积的方式,从左到右,依次作用到可迭代对象的每个元素上,还能指定初始值
reduce(function, sequence)
Docstring:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
reduce(lambda x, y: x + y, [1,2,3,4,5]) # reduce() 需要从 functools 模块导入
# 计算过程为:((((1+2)+3) +4)+5)
15
mm = lambda x, y: x **2 + y ** 2 # 两个数的平方和
reduce(mm, tuple(range(10)))
160623854392948285208011982134507489923477046669785452499236264188406112786126885439804859615624545
add = lambda x,y: x+y
reduce(add, range(101)) # 累加
5050
过滤函数filter(fun, sequence)将单参数函数作用于序列的每个元素,返回使函数返回值为True的那些filter对象
filter(function or None, sequence)
Docstring:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
# 过滤出字符串里面的数字
seq = ['jsdj8', 'ccj7', '??', '!','12,4jjjk']
list(filter(lambda s: s.isdigit(), seq))
[]
seq = ['foo', 'x41', 'z..??', '**4?!666'] # 需要将里面的元素,是数字or字母的 过滤出来
filter(lambda s: s.isalnum(), seq) # string.isalnum() 判断是否为字母或数字,等同于 s.isalpha() or s.isdigit()
<filter at 0xa55497d550>
Docstring:
S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
list(filter(lambda s: s.isalnum(), seq))
['foo', 'x41']
seq # 不对元列表做任何修改
['foo', 'x41', 'z..??', '**4?!666']
list(filter(None, [1,2,5,0,4,0,3,0,3,0,0,0,3])) # 过滤掉0
[1, 2, 5, 4, 3, 3, 3]
range()函数
range(start, end, step) 返回具有惰性求值特点的range对象,前闭后开
range(5)
range(0, 5)
list(_)
[0, 1, 2, 3, 4]
list(range(1, 10, 2)) # 起始值为1,步长为2
[1, 3, 5, 7, 9]
list(range(9, 0, -2)) # step<0时,start > end
[9, 7, 5, 3, 1]
for _ in range(4): # 常用range()函数来控制循环次数
print(666, end=' ')
666 666 666 666
# 输出200以内,能被17整除的最大整数
for i in range(200,170, -1):
if i % 17 == 0:
print(i)
187
zip()打包函数
zip(iter1,iter2,iter3,,)将多个序列元素左对齐,然后想拉链一样往右拉,相同位置元素组合成元组,长度取决于最短序列
Init signature: zip(self, /, *args, **kwargs)
Docstring:
zip(iter1 [,iter2 [...]]) --> zip object
Return a zip object whose .next() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .next()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration
list(zip('abcde', [1,2,3,4,5,6,7]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
dict(zip('abcde', [1,2,3,4,5,6,7])) # 作为键值对 组合成字典
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
list(zip('abcde', [1,2,3,4,5,6,7], (666,666,4,5,6,))) # 多个维度的,类似多个坐标值
[('a', 1, 666), ('b', 2, 666), ('c', 3, 4), ('d', 4, 5), ('e', 5, 6)]
x = zip('abc', '1,2,4,5')
list(x)
[('a', '1'), ('b', ','), ('c', '2')]
list(x) # zip对象只能遍历一次
[]
eval()函数
eavl(string)计算字符串里边表达式的值,也常用来实现类型转换
Signature: eval(source, globals=None, locals=None, /)
Docstring:
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
Type: builtin_function_or_method
eval("1 + 1")
2
eval('666')
666
eval(str({'cj':3, 'age':22})) # 1.将字典转为字符串;2、再用eval()将字符串里的值转换出来 名片管理系统会用到
{'cj': 3, 'age': 22}
精彩案例
将一个3位数,输出它的百位、十位、个位上的数字
# 取整、取余法
g = 123 % 10
s = 123 // 10 % 10
b = 123 // 100
print("个位是:%d, 十位是:%d, 百位是: %d" % (g, s, b))
个位是:3, 十位是:2, 百位是: 1
# 字符串法
x = 123
a,b,c = map(int, str(x))
print(a, b, c)
已知三角形的两边边长及其夹角,求第三边长(余弦定理)
import math
s = input("请输入两边边长及夹角(度):\n")
a,b,theta = map(float, s.split())
# 余弦定理
c = a**2 + b**2 - 2*a*b*math.cos(theta*math.pi/180)
print('第三边c的长度是:', c)
请输入两边边长及夹角(度):
4 5 60
第三边c的长度是: 20.999999999999996