Jupyter中Python的基础学习

本篇博客只是记录一下学习Python过程中的基础知识点,想深入了解Python,可到Python官网进行阅读学习。

1.关于类型Python自己决定类型

print("hello world")
输出:
hello world  
#判断是Python2还是Python3 可由简单的print()内置函数判断  print()输出的为Python3
x=1
print(type(x))
输出:
<class 'int'>  # type()为Python中的内置函数 作用判断对象类型
x=1.1
print(type(x))
输出:
<class 'float'>  #Python中默认为浮点型

2.关于字符串类型

y='123a'
print(type(y))
print(y)
输出:
<class 'str'>   #str 为Python中的字符串类型   ''可代表字符串类型
123a
y="123a"
print(type(y))
print(y)
输出:
<class 'str'>  #str 为Python中的字符串类型   “”可代表字符串类型
123a
y="""123a"""
print(type(y))
print(y)
输出:
<class 'str'>  #str 为Python中的字符串类型   """"""也可代表字符串类型
123a

3.关于字节串

z =b'hell word'
print(type(z))
print(z)
输出: 
<class 'bytes'>
b'hell word'  #bytes 为Python中的字节类型  用b代表字符串为字节型
#注意 Jupyter中一个cell只能输出一个结果,如需输出多个结果 需使用内置函数print()

4.关于列表 相当于java中的list

x=[1,2,3]
print(x)
print(x[0])
输出: 
[1, 2, 3] 
1 #相当于java中的list  动态长度可变  有序 下标从0开始

5. 字典 相当于java中的Map

x={"a":"张三","b":"李四"}  # Python中的字典  基于键值对形式  相当于java中的map
x
输出: 
{'a': '张三', 'b': '李四'}
x["a"]  #js的字典  x[文字下标]
输出: 
'张三'

6. 元组 相当于不可改变的list

x=(1,2,3)
x
输出: 
(1, 2, 3)
# 相当于不可改变的list 
x[0]  # 元组元素访问 用下标  0开始
输出:
1
x[0]=1111  #不可改变
输出:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-7ad8eb1591f4> in <module>
----> 1 x[0]=1111  #不可改变

TypeError: 'tuple' object does not support item assignment

7.set,fronzenset -> set相当于java的set(不可重复 无序),fronzenset 是不可以改变的

x={'a','b','c','d'}
print(x)
print(type(x))
输出:
{'a', 'b', 'c', 'd'}
set
#相当于java中的set   元素不可重复  无序  不可改变  可以放到字典中当键用(即可以hash)

python中的变量

1.关于赋值

x=3
print(x**3)
输出:
27
#python 中可以可以累乘

2.允许多个变量指向同一个值

x=3
id(x)  #id() 是Python语言的内置函数  用于输出一个对象的hash码
输出:
140720922927568
y=x
id(y)
输出:
140720922927568
 #引用传递  就是把hashcode的地址引用传递过来  不改变原值
x+=6
id(x)
输出:
140720922927760
# 值传递 当给x重新赋值,它的内存地址就会改变  
id(y) #y的地址不会改变
输出:140720922927568

3.python采用的是基于值的内存管理方式

x=3
id(x)
输出:
140720922927568
y=3
id(y)
输出:
140720922927568
#小结 在Python中 如果值相同 则使用同一个内存空间
x=[1,1,1,1]
id(x[0])==id(x[1])
输出:
True
#python是完全面向对象的语言
#小结:Python自动内存管理 对于没有任何变量引用的值,Python会自动删除.
# 相当于java当中的垃圾回收机制

4.Python变量名规范

1.字母,下划线开头(Python中的下划线有特殊含义)
2.变量名不能有空格,标点
3.不能有关键字
4.不能用Python模块名(java中的包),类型名,函数名
5.大小写敏感
#关于Python中的关键字
import keyword
print(keyword.kwlist)
输出:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
#用import导入Python中的关键字  再使用print()内置函数输出
#输出python的内置函数,类型和模型
dir(__builtins__) 
输出:
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 ...
 #__xxx__  代表的是Python内置  dir()也是Python内置函数  
#使用 dir()函数可以查看对象内的所有的属性和方法,在 python 中任何东西都是对象,一种数据类型,
一个模块等,都有子集的属性和方法,除了常用的方法外,其他的你不需要全部记住它,交给 dir() 
函数就好了。

5.关于字符串

#1.字符串合并
a='abc'+"123" 
a
输出:
'abc123'
# 字符串可使用+ 符号连接
x='1234''abc' #常量可以自动合并
x
输出:
'1234abc'
x=x'xxx' #变量不可自动合并
x
输出:

```handlebars
  File "<ipython-input-55-f6631fe32bce>", line 1
    x=x'xxx' #变量不可自动合并
           ^
SyntaxError: invalid syntax

#2.格式化处理   format("%d %s")  占位符
a=3.6675  
print('%-7.3f' %a)  # f:代表float浮点型   i:代表int类型  s:代表字符串  
输出:
3.667  
 # 小数点后一半进位(超过5)      3表示小数点保留几位   7表示数据总长度   -表示左对齐
# f浮点数   d整数   c字符  s字符串
print("%d:%c" %(65,65))
print("my name is %s,and my age is %d" %('fangxiang',20))  #()表示元组
输出:
65:A
my name is fangxiang,and my age is 20
# 转义符   \n 代表换行    \r 回车符
print('hello\nworld\rfangxiang')
输出:
hello
fangxiang
# 转义符   \n 代表换行    \r 回车符  \r回车 回到这行开头将world覆盖
print('\102')  #字节
print('\x42')  #16进制
print('我是\u3456\u1111') #unicode字符表
输出:
B
B
我是㑖ᄑ
#1 输出所有的汉字的unicode 范围
for i in range(65536):   #range()  内置函数  作用 0 到n-1
    if i%10==0:
        print('\n')
    print(str(i),chr(i))
    输出:
    0 
1 
2 
3 
4 
5 
6 
7 
8
9 
...
# 2 以unicode码输出程序员三个字
print(ord("程") ,ord("序"),ord("员"))
print(chr(31243),chr(24207),chr(21592))
输出:
31243 24207 21592
  
#3 \代表转义
path='c:Windows\text.txt'  #\代表转义
print(path)
输出:
c:Windows	ext.txt
#4 .r达标原始字符串  在正则表达式中会大量使用
path=r'c:Windows\text.txt' 
print(path)
输出:
c:Windows\text.txt

6.运算符

# +   列表的追尾添加  运算符重载
[1,2,3]+[4,5,6]
输出:
[1, 2, 3, 4, 5, 6]
# +   元组的追尾添加
(1,2,3)+(4,)
输出:
(1, 2, 3, 4)
'A'+1 #Python中不能将数字与字符相加
输出:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-3e6343ae0214> in <module>
----> 1 'A'+1 #Python中不能将数字与字符相加

TypeError: can only concatenate str (not "int") to str

True+1
输出:
2
#Python中True+1  =2
False+1
输出:
1
#Python中False+1  =1
# *符号
2.0*3
输出:
6.0
(3+4j)*2
输出:
(6+8j)
"a"*10  #字符串中叫做重复
输出:
'aaaaaaaaaa'
[1,2,3]*3  #列表重复3
输出:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
(1,2,3)*3  #元组重复3
输出:
(1, 2, 3, 1, 2, 3, 1, 2, 3)
#  / 除法  //  整数除法  
3/5  #Python中得到小数
输出:
0.6
-13//10  #-13除以10等于-1.3 偏于负无穷最小等于-2
输出:
-2
# %
'''
 % 格式化字符串  '%d' %12
 % 求余数
'''
print(3.1%2)
print(6.3%2)
print(7%3)
输出:
1.1
0.2999999999999998
1
# 关系运算符  java中: 1<x<5  错误    1<x && x<5
#Python 中可以连用
print(1<3<5)
输出:
True
print ('hello'>'world') # h比w要小  按字符比较
输出:
False
print([1,2,30]<[1,2,4])  #列表也可以比较
输出:
False
print('hello' >3) #字符串与数字不能进行比较
输出:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-69e011c57001> in <module>
----> 1 print('hello' >3) #字符串与数字不能进行比较

TypeError: '>' not supported between instances of 'str' and 'int'
#< 这个<符号指的是集合的运算
print({1,2,3000}<{1,2,33,4})  #{}表示集合  这是一个集合的运算{交,并,差}
输出:
False
# in  成员测试
print(3 in [1,2,3])
输出:
True
r1=range(1,10,1) #迭代器  range(start,end,step)
r1  #range对象  惰性求值的对象   是一个iterator对象
输出:
range(1, 10)
for i in range(1,10,2):  #1,3,5,7,9
    print(i)
    输出:
    1
	3
	5
	7
	9
l=list(range(1,11,1))  #可以转为可以运算的对象
l
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(5 in range(1,10,2))
输出:
True
# in 循环
for i in [1,2,3]:
    print(i)
    输出:
    1
	2
	3
#is 运算符  测试两个对象是否是同一个
print(3 is 2)
输出:
False
x=[200,200,200]
print(x[0] is x[1])
输出:
True
x=[1,2,3]
y=[1,2,3]
print(x is y)
print(id(x),'',id(y)) #常量区中的hash地址不同
输出:
False
2654323327240  2654323351240
#集合 set  fronsenset中的交,并,差
print({1,2,3} |{3,4,5}) #并集
输出:
{1, 2, 3, 4, 5}
print({1,2,3}&{3,4,5}) #交集
输出:
{3}
print({1,2,3}-{3,4,5}) #差集
输出:
{1, 2}
print(3 and 5<2)
#运算符的优先级  5<2false  
输出:
False
# , 逗号运算符  ,分隔符
print('a' in 'b','a')  #print(*args) print语法决定里面含有多个参数
输出:
False a
x=3,5
x
#逗号运算符优先
输出:
(3, 5)
3==3,5
# 关系运算符优先逗号运算符
输出:
(True, 5)
x=3+5,7
x
#加号运算符优先逗号运算符 
输出:
(8, 7)
# ++  -- Python中不支持  虽然可以这样写  但不熟自增,自减的意义
i=3
print(++i) #写在前面  代表正正得正
输出:
3
print(i--) #写在后面报错 Python中不支持
输出:
  File "<ipython-input-50-8a0445d73b09>", line 1
    print(i--)
             ^
SyntaxError: invalid syntax

#在Python中 任何类型的对象或常数  属于合法表达式,使用运算符连接的变量和
#常量及函数调用都是合法的表达式
a=[1,2,3]
b=[4,5,6]
c=a+b
c
输出:
[1, 2, 3, 4, 5, 6]
# map(function, iterable,...)
m=map(str,c) #这种map对象是一个惰性求值的对象  只能使用一次  相当于spark转化操作
print(m)
输出:
<map object at 0x0000026A020D6808>
r=list(m)  #相当于spark一次动作操作
r
输出:
['1', '2', '3', '4', '5', '6']
# map(str,c)  循环c列表 将c中的每个元素提取出来  调用str(元素)对元素进行类型转换(转成字符串)
d=list(map(str,c))
d
输出:
['1', '2', '3', '4', '5', '6']
import math
list(map(math.sin,c)) #math.sin 是一个函数  math.sin(c[0])  math.sin(c[1])  math.sin(c[2])
#返回的x弧度的正弦值,数值在 -1  1 之间。
输出:
[0.8414709848078965,
 0.9092974268256817,
 0.1411200080598672,
 -0.7568024953079282,
 -0.9589242746631385,
 -0.27941549819892586]
('welcome,'*3).rstrip(',')+'!'
#返回删除 string 字符串末尾的指定字符后生成的新字符串。
输出:
'welcome,welcome,welcome!'

7.内置函数

import keyword
#dir () 返回指定对象或模块obj的成员列表,如果不带参数则返回当前作用域内所有标识符
print(dir()) #当前作用域内所有的的标识符(模板,类,变量,函数)
print(dir(keyword)) #这个keyword模块中所有的参数
输出:
['In', 'Out', '_', '_1', '_10', '_11', '_12', '_13', '_14', '_15', '_16', '_17', '_18', '_19', '_30', '_34', '_4', '_46', '_47', '_48', '_5', '_51', '_52', '_53', '_6', '_64', '_65', '_66', '_67', '_68', '_69', '_70', '_71', '_75', '_78', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_i29', '_i3', '_i30', '_i31', '_i32', '_i33', '_i34', '_i35', '_i36', '_i37', '_i38', '_i39', '_i4', '_i40', '_i41', '_i42', '_i43', '_i44', '_i45', '_i46', '_i47', '_i48', '_i49', '_i5', '_i50', '_i51', '_i52', '_i53', '_i54', '_i55', '_i56', '_i57', '_i58', '_i59', '_i6', '_i60', '_i61', '_i62', '_i63', '_i64', '_i65', '_i66', '_i67', '_i68', '_i69', '_i7', '_i70', '_i71', '_i72', '_i73', '_i74', '_i75', '_i76', '_i77', '_i78', '_i79', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'b', 'c', 'd', 'exit', 'fang', 'get_ipython', 'i', 'keyword', 'l', 'm', 'math', 'quit', 'r', 'r1', 'x', 'y']
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'kwlist', 'main']
import random
help(random)
#help() 对象obj的帮助文档  相当于java中的api
输出:
Help on module random:

NAME
    random - Random variable generators.
    ...
# 数字转换  bin()  oct()   hex()   2进制  8进制 16进制
print(bin(5))
print(oct(5))
print(hex(5))
输出:
0b101
0o5
0x5
# ord(char)  返回1个字符的Unicode编码
# chr(unicode) 返回Unicode编码为x的字符
print(ord('a'))
print(chr(ord('a')+1))
#str(x)  将任意类型的x转为字符串
print(str((1,2,4))) #将一个元组转为字符串
print(type(str((1,2,4))))
输出:
97
b
(1, 2, 4)
<class 'str'>
#需求:随机生成10位数 存在列表中 取最大值 最小值 求和
print(random.randint(1,100))
arr=[]
for i in range(0,10):
    arr.append(random.randint(1,100))
print(arr)
print(max(arr),min(arr),sum(arr))
输出:
64
[64, 44, 4, 2, 4, 33, 67, 25, 28, 7]
67 2 278
#方案二 python 精神
#列表推导生成式  :生成列表
arr2=[ random.randint(1,100) for i in range(0,10)]
print(arr2)
print(max(arr2),min(arr2),sum(arr2))
#求平均值
print(sum(arr2)/len(arr2))
输出:
[71, 25, 55, 78, 88, 2, 97, 30, 99, 52]
99 2 597
59.7
# max() min()的key参数可以用来指定比较规则
x=['2221','1234','9','99'] #判断元素的类型  string 类型sort
print(max(x))
print(max(x,key=len)) #key是一个函数function  按照长度比较大小
print(max(x,key=int))#key是一个函数function  按照整型比较大小
输出:
99
2221
2221
# 结合前面的列表推导式,随机数生成器  max()函数
#需求:求二维数组中所有的元素和最大的子列表
x=[ [random.randint(1,100) for i in range(0,10)] for j in range(0,5)] #510列的二维数组
for item in x:
    print(item,' ',sum(item))
print(max(x))
print(max(x,key=sum))
输出:
[97, 30, 4, 77, 21, 36, 14, 84, 52, 52]  467
[49, 10, 28, 70, 78, 68, 28, 88, 89, 72]  580
[89, 39, 91, 83, 20, 51, 58, 4, 16, 19]  470
[65, 58, 73, 100, 8, 60, 92, 25, 25, 54]  560
[64, 8, 74, 60, 17, 54, 11, 69, 63, 70]  490
#sum(x ,start=0)  返回序列中x所有元素之和,返回start+sum(x)
print(sum([1,2,3,4]))
print(sum([1,2,3,4],20)) # 10+20

arr2=[[1,2,3],[2,3,4],[3,4,5]]
#print(sum(arr2))
print(sum(sum(arr2,[])))
输出:
10
30
27

8. 内置函数type() 和isinstance()可以判断数据类型

type([3])  #查看[3]的类型
# isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()
# isinstance()  type() 区别:
# type() 不会认为子类是一种父类类型,不考虑继承关系。
# isinstance() 会认为子类是一种父类类型,考虑继承关系。
输出:
list
type({3}) in(set,list,map,dict) #判断3是否属于
输出:
True
isinstance (3,int) #判断3是否为int类型的实例
输出:
True
isinstance(3j,(int,float,complex)) #判断3j是否为int,float或complex实例
输出:
True

9. sorted()对列表、元组、字典、集合或其他可迭代对象进行排序并返回新刷新列表

# sorted(iterable,*,key=None,reverse=False)
x=['aaa','bc','Ab','AB','ba']
print(sorted(x)) #默认升序
print(sorted(x,key=len)) #按长度排序
print(sorted(x,key=str)) #按字符串排序
print(sorted(x,key=str.lower)) #按小写排序
输出:
['AB', 'Ab', 'aaa', 'ba', 'bc']
['bc', 'Ab', 'AB', 'ba', 'aaa']
['AB', 'Ab', 'aaa', 'ba', 'bc']
['aaa', 'Ab', 'AB', 'ba', 'bc']

10. reversed()对可迭代对象(生成器对象和具有惰性求值特性的zip/map/filter/enumerate等类似对象除外)进行翻转(首尾交换) 并返回可迭代的reversed对象

# reversed(seq)  Return a reverse iterator.说明它是一个惰性求值对象
x=['aaaa','bb','cc','ddd']
print(reversed(x))
print(list(reversed(x)))
输出:
<list_reverseiterator object at 0x0000026A020D3108>
['ddd', 'cc', 'bb', 'aaaa']

11. range()函数,惰性求值得到range对象

print(range(5))
print(type(range(5)))
print(list(range(5)))
print(range(0,5,3))
print(list(range(0,5,2)))
输出:
range(0, 5)
<class 'range'>
[0, 1, 2, 3, 4]
range(0, 5, 3)
[0, 2, 4]

12. enumerate()枚举 返回可迭代的enumerate对象 每个元素都包含(索引,值)的元组

# enumerate(iterable,start=0)
print(enumerate('abcde')) 
print(list(enumerate('abcde')))
for index,value in enumerate('abcde'):
    print(index,":",value)
print(list(enumerate([1,2,3,4,5])))
输出:
<enumerate object at 0x0000026A020D2C28>
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
0 : a
1 : b
2 : c
3 : d
4 : e
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

13. map映射,将一个函数参数映射到序列

# map(function,iterable,...)
print(list(map(str,range(5)))) # str是内置函数 star(参数)
输出:
['0', '1', '2', '3', '4']
#用户自定义的函数:将数字+10
def addTen(num):
    return num+10
print(list(map(addTen,range(5))))
输出:
[10, 11, 12, 13, 14]
# map(function,iterable,...)
def addTen2(num1,num2):
    return num1+num2
print(list(range(10,19)))
print(list(map(addTen2,range(5),range(10,19))))
# iterable,...表示要同时循环的集合...,如果循环几个集合,那么调用的函数就有几个参数
输出:
[10, 11, 12, 13, 14, 15, 16, 17, 18]
[10, 12, 14, 16, 18]
# 使用lambda :匿名函数,有返回值
laml=lambda num:num+10
print(list(map(laml,range(5))))
print(list(map(lambda num:num+10,range(5)))) #匿名函数可以写在map中
print(list(map(lambda _:_+10,range(5)))) #可以用下划线代替参数
输出:
[10, 11, 12, 13, 14]
[10, 11, 12, 13, 14]
[10, 11, 12, 13, 14]
lam2=lambda num1,num2:num1+num2
print(list(map(lam2,range(5),range(10,15))))
print(list(map(lambda num1,num2:num1+num2,range(5),range(10,15))))
print(list(map(lambda _1,_2:_1+_2,range(5),range(10,15))))
输出:
[10, 12, 14, 16, 18]
[10, 12, 14, 16, 18]
[10, 12, 14, 16, 18]
#小项目,请包装map 提供一个将一个序列与数字进行四则运算
# iterable op-> '+','-','*','/', value 数字
# 将iterable中每个元素取出与value进行op运算
# 1.如何将 1'+'5 运算, 使用eval(字符串的表达式)
# 2.map(函数,iterable)
# 3.函数 -> eval(str(元素)+op+str(value))
# 4.用lambda实现以上函数
def myMap(iterable,op,value):
    if op not in ['+','-','*','/','//','**']:
        return 'Error operator'
    lam1=lambda _:eval(str(_)+op+str(value))
    return map(lam1,iterable)

print(myMap([1,2,3],'+',5))
print(list(myMap([1,2,3],'+',5)))
print(list(myMap([1,2,3],'!',5)))
输出:
<map object at 0x0000026A021211C8>
[6, 7, 8]
['E', 'r', 'r', 'o', 'r', ' ', 'o', 'p', 'e', 'r', 'a', 't', 'o', 'r']
# 小项目需求:取出一个整数的每一位  123 1 2 3
x=random.randint(1,1e30)
print(x)
print(list(str(x)))
print(list(map(int,str(x))))
输出:
370733276449661715530208486990
['3', '7', '0', '7', '3', '3', '2', '7', '6', '4', '4', '9', '6', '6', '1', '7', '1', '5', '5', '3', '0', '2', '0', '8', '4', '8', '6', '9', '9', '0']
[3, 7, 0, 7, 3, 3, 2, 7, 6, 4, 4, 9, 6, 6, 1, 7, 1, 5, 5, 3, 0, 2, 0, 8, 4, 8, 6, 9, 9, 0]

14. 标准库functools中的函数reduce()可以将一个接收2个参数的函数以迭代累积的方式从左到右依次作用到一个序列或迭代器对象的所有元素上,并且允许指定一个初始值

from functools import reduce
seq=list(range(1,100))
print(seq)
print(reduce(lambda _1,_2:_1+_2,seq)) #reduce 归并
输出:
[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, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
4950
# operator类 操作符
# .add() sub() mul() div()  代表加减乘除
import operator
print(operator.add(1,2)) #加法
print(operator.sub(1,2)) #减法
print(reduce(operator.add,seq)) #通过operator类可以将普通的运算转为函数,这样就可以作为回调函数使用了
# 10的阶乘
print(reduce(operator.mul,range(1,11)))
输出:
3
-1
4950
3628800

15. 内置函数filter()将一个单参数函数作用到一个序列上,返回该序列中使得函数返回值为True的哪些元素组成的filter对象,如果指定函数为None,则返回序列中等价于True的元素

# filter(function,iterable)
seq=['smith','x43','23','!?','***']
def func(value):
    return value.isalnum() # 判断是否为字母或者数字
print(filter(func,seq))
print(list(filter(func,seq)))

seq2=[33,55,77,85]
print(list(filter(lambda _:_>60,seq2)))
输出:
<filter object at 0x0000026A020CD288>
['smith', 'x43', '23']
[77, 85]

16. zip()函数用来把多个可迭代对象中的元素压缩到一起,返回一个可迭代的zip对象,其中每个元素都是包含原来多个可迭代对象对应位置上元素的元组,如同拉拉链一样

print(zip('abc',[1,2,3]))
print(list(zip('abc',[1,2,3])))
print(list(zip('sdasd',[1,2,3,4],[4,5,6,7,8,9])))
输出:
<zip object at 0x0000026A020CDC88>
[('a', 1), ('b', 2), ('c', 3)]
[('s', 1, 4), ('d', 2, 5), ('a', 3, 6), ('s', 4, 7)]

17. map、filter、enumerate、zip、range等对象不仅具有懒惰型求值的特点,还有另外一个特点:访问过的元素不可再次访问

x=map(str,range(10))
print(list(x))
print(list(x))
x=map(str,range(10))
x=list(x)
print(x)
print(x)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
[]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

猜你喜欢

转载自blog.csdn.net/weixin_44422604/article/details/107486359