【python基础学习2】python里和可迭代对象iterator相关的函数:zip(), map(), join() 函数和strip()方法等

本文主要是介绍【python基础学习2】python里和可迭代对象iterator相关的函数:zip(), map(), join() 函数和strip()方法等,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 目录

1 python里的可迭代对象

1.1 什么是可迭代对象

1.2 python里的可迭代对象

1.3 可迭代对象如何遍历

1.3.1 可迭代方法

1.3.2 迭代器的测试

2 zip()函数:

我愿理解zip()为一个矩阵横向和纵向两种组合方式转化

2.1 zip() 函数定义

2.2 zip()函数的效果

2.3 zip() 函数和 zip(*) 函数

2.4 测试代码

3 map()函数

3.1 map()函数

3.2  测试代码1

3.3 对应iteator, 除了使用map() 函数,用list的闭包形式也可以达到相同效果

4 str.strip() 字符串的strip()方法

4.1 str.strip() 的方法

4.2 奇怪的内容:(原因不明,看起来只有str.strip() 符合要求)

4.3 测试代码

5 join() 函数:  分隔符号.join(iteator) 返回字符串

5.1 基本语法,分隔符号.join(iteator)

5.2 iteator可以是闭包或各种返回为迭代器都可以


1 python里的可迭代对象

1.1 什么是可迭代对象

  • 可循环遍历的就是可迭代的
  • 也就是可以使用for循环遍历它们的对象
  • 写个for循环就可以遍历的这种,python里还可以用list() 遍历更方便
  • 可迭代的:iterable
    • 可迭代的对象: iterable object
    • 迭代器:            iterator

1.2 python里的可迭代对象

  • list
  • tuple
  • string        #字符串天然按其前后次序可迭代
  • dictionary
  • set
  • 也可以自定义可迭代对象

1.3 可迭代对象如何遍历

  • python里对可迭代对象的遍历是很方便的
  • 最简单的遍历方法有如下几种:

1.3.1 可迭代方法

  • 方法1:直接输出迭代器iterator

iterator

#一般只会返回其 object 及其物理地址,而不会返回其 迭代的内容

  • 方法2:直接用print()函数

# print(iterator)

#在jupyter notebook 可以直接输出迭代内容

# 其他IDE不确定?

  • 方法3:使用 for 循环对其进行遍历迭代器iterator:

for x in iterator:

    print(x)

  •  方法4:直接使用list的闭包形式[]:
print([a for a in A2])
  • 方法5:使用 list() 函数,将迭代器转换为一个列表:

list(iterator)

print(list(iterator))

1.3.2 迭代器的测试

A=[1,2,3]print("\nA=",end="")
Aprint("\nprint(A)=",end="")
print(A)print("\nfor a in A:=",end="")
for a in A:print(a)print("\n[a for a in A]=",end="")
print([a for a in A])print("\nlist(A)=",end="")   
print(list(A))

 输出结果

A=
print(A)=[1, 2, 3]for a in A:=1
2
3[a for a in A]=[1, 2, 3]list(A)=[1, 2, 3]

2 zip()函数:

我愿理解zip()为一个矩阵横向和纵向两种组合方式转化

2.1 zip() 函数定义

  • zip()函数:我愿理解zip()为一个矩阵横向和纵向两种组合方式转化
  • zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素(index相同)打包成一个个元组,然后返回由这些元组组成的列表。
  • 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
  • zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。

2.2 zip()函数的效果

  • zip()函数的效果:把几个数组,排列后,把index相同的排成新的数组,多余的丢弃
  • 效果相当于 矩阵按行排列,修改为按列去排。

2.3 zip() 函数和 zip(*) 函数

  • 下面两者互为逆运算
  • c=zip(a,b)
  • zip(*c)=a,b

2.4 测试代码

# 可迭代对象:iterable object
# 可迭代对象:list,tuple,stringa=[1,2,3]
b=[4,5,6]
c="abcdefgh"print(a)
print(zip(a,b))
print(list(zip(a,b)))
print()print(c)
print(list(c))
print(zip(a,c))
print(list(zip(a,c)))#可见,在zip()这
#string就等同于list(string),都是可迭代对象
#但是这2个对象,从名称看还是有差别的 25880> 125740>
print(zip(a,list(c)))
print(list(zip(a,list(c))))
print()zip(*zip(a,b))
print(zip(*zip(a,b)))
print(list(zip(*zip(a,b))))
print(list(zip(*zip(a,c))))

[1, 2, 3]
<zip object at 0x0000022DADAC4B40>
[(1, 4), (2, 5), (3, 6)]abcdefgh
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
<zip object at 0x0000022DADAC4B40>
[(1, 'a'), (2, 'b'), (3, 'c')]
<zip object at 0x0000022DAE0F3D80>
[(1, 'a'), (2, 'b'), (3, 'c')]<zip object at 0x0000022DAE0F3D80>
[(1, 2, 3), (4, 5, 6)]
[(1, 2, 3), ('a', 'b', 'c')]

3 map()函数

3.1 map()函数

  • map(function, iterable)
  • map()函数用于将函数映射到可迭代对象中的每个元素可迭代对象中的每个元素
  • 对于可迭代对象中的每个元素应用该函数,函数返回值包含在生成的map对象中。
  • 第一个参数接受一个函数名,后面的参数接受一个或多个可迭代的序列(列表,元组,集合),返回的是一个集合。即后边的可迭代对象中的每个元素依次作用到函数,并返回输出值构成一个集合。


3.2  测试代码1

  • map(function, iterator)
  • 其中function可以有很多种类型
  1. function=自定义函数
  2. function=匿名函数:
    • map(lambda item: [item[0], item[1], item[1] * TAX], carts)
    • lambda x,y:x*y
  3. function=none:这也可以?
  4. function=系统函数:比如 int
  5. str.strip 
  6. 等等也可以
  • iterator
  1. list
  2. string
  3. tuple
  4. dictionary
  5. ...

#map(function,iterable) 将函数映射到可迭代对象上#可使用自定义函数
def square(x):return x**2
a=map(square,[1,2,3])
a
print(a)
print(list(a))#lambda 匿名函数也行
a=map(lambda x,y:x*y,[1,2],[3,4])
print(list(a))names = ['david', 'peter', 'jenifer']
new_names = map(lambda name: name.capitalize(), names)
print(list(new_names))#复杂一点的
carts = [['SmartPhone', 400],['Tablet', 450],['Laptop', 700]]
TAX = 0.1
carts = map(lambda item: [item[0], item[1], item[1] * TAX], carts)
print(list(carts))#允许映射到多个可迭代对象
a=map(lambda x,y:(x*y,x+y),[1,2],[3,4])
print(list(a))#没有函数时,类zip()函数??
a=map(None,[1,2],[3,4])
#print(list(a))  #TypeError: 'NoneType' object is not callable#对字符串这种对象
string = "Hello World"
result = list(map(str.strip, string))
print(result)string = "Hello World"
a = map(str.strip, string)
print(list(a))#对元组
a=map(int,(1,2,3))
print(list(a))   #ValueError: invalid literal for int() with base 10: 'a'#对字典这种可迭代对象
a=map(int,{'a':1,'b':2,'c':3})
#print(list(a))#对字典的keys,values的映射
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
a = map(lambda x: x[0], my_dict.items())
b = map(lambda x: x[-1], my_dict.items())
print(list(a))
print(list(b))#字典本身的方法也可以做到一样的效果
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
a=my_dict.keys()
b=my_dict.values()
print(list(a))
print(list(b))

运行结果
<map object at 0x0000022DAF27D240>
[1, 4, 9]
[3, 8]
['David', 'Peter', 'Jenifer']
[['SmartPhone', 400, 40.0], ['Tablet', 450, 45.0], ['Laptop', 700, 70.0]]
[(3, 4), (8, 6)]
['H', 'e', 'l', 'l', 'o', '', 'W', 'o', 'r', 'l', 'd']
['H', 'e', 'l', 'l', 'o', '', 'W', 'o', 'r', 'l', 'd']
[1, 2, 3]
['name', 'age', 'city']
['Alice', 25, 'New York']
['name', 'age', 'city']
['Alice', 25, 'New York']

3.3 对应iteator, 除了使用map() 函数,用list的闭包形式也可以达到相同效果

A1=[1,2,3]print([a for a in A1])
print([a**2 for a in A1])
输出结果
[1, 2, 3]
[1, 4, 9]

4 str.strip() 字符串的strip()方法

4.1 str.strip() 的方法

  • #错误写法:在python不是独立的函数,   str1=strip(str1)
  • #正确写法:是字符串.方法(),   str1=str1.strip()

  • string.strip()   
  • 方法必须是none 或者是string,不能是数字123这种
  • 不带参数的
  • 删除字符串首尾的指定字符,如果为空则是各种空白/n, /r, /t, ' '等
     

4.2 奇怪的内容:(原因不明,看起来只有str.strip() 符合要求)

  • 下面3种用法,语法上都OK,但是结果不相同
  • string.strip()   
  • str.strip()                     #从结果上看,正确用法
  • str1.strip()   

str1=" hello world "                    #原字符串:13个字的字符串,包含边上2个空格

str2=map(string.strip,str1)        # 返回:13个没有两边空格的字符串,把原字符串映射了n次?

str3=map(str.strip,str1)             # 返回:会分切为13个单个字母,符合一般的需求

str4=map(str1.strip,str1)           # 返回:1个没有两边空格的字符串+12个有两边空格的原字符串,把原字符串映射了n次?

  • str2=map(string.strip,str1)对应结果
    • <map object at 0x0000022DAF288460>
    • ['Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello Worl', 'Hello World']
  • str3=map(str.strip,str1)对应结果
    • <map object at 0x0000022DAF288AF0>
    • ['', 'h', 'e', 'l', 'l', 'o', '', 'w', 'o', 'r', 'l', 'd', '']
  • str4=map(str1.strip,str1)对应结果
    • <map object at 0x0000022DAF28A020>
    • ['hello world', ' hello world ', ' hello world ', ' hello world ', ' hello world ', ' hello world ', 'hello world', ' hello world ', ' hello world ', ' hello world ', ' hello world ', ' hello world ', 'hello world']

4.3 测试代码


# string.strip()   
#方法必须是none 或者是string,不能是数字123这种
str1 = "3233121Hello World123456333211"
str1.strip("123")  #TypeError: strip arg must be None or str
print(str1.strip("123"))# 不带参数的
# 删除字符串首尾的指定字符,如果为空则是各种空白/n, /r, /t, ' '等
str1 = "  3233121  Hello World  123456333211"
print(str1.strip())
print()str1=" hello world "
#错误写法:不是独立的方法, str1=strip(str1)
#正确写法:是字符串.方法(), str1=str1.strip()#string.strip 这个方法效果匪夷所思
str2=map(string.strip,str1)
str2
print(str2)
print(list(str2))
print()#str.strip 切成一个个字符
str3=map(str.strip,str1)
str3
print(str3)
print(list(str3))
print()#str.strip 切成一个个字符
str4=map(str1.strip,str1)
str4
print(str4)
print(list(str4))
print()

输出结果

Hello World123456
3233121  Hello World  123456333211<map object at 0x0000022DAF288460>
['Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello World', 'Hello Worl', 'Hello World']<map object at 0x0000022DAF288AF0>
['', 'h', 'e', 'l', 'l', 'o', '', 'w', 'o', 'r', 'l', 'd', '']<map object at 0x0000022DAF28A020>
['hello world', ' hello world ', ' hello world ', ' hello world ', ' hello world ', ' hello world ', 'hello world', ' hello world ', ' hello world ', ' hello world ', ' hello world ', ' hello world ', 'hello world']

5 join() 函数:  分隔符号.join(iteator) 返回字符串

5.1 基本语法,分隔符号.join(iteator)

  • 分隔符号.join(iteator)
  • 分隔符号
  • iteator,迭代器
  • 返回:字符串
items = ['apple', 'banana', 'orange']
separator = ', '
result = separator.join(items)
print(result)
out: 
apple, banana, orange

5.2 iteator可以是闭包或各种返回为迭代器都可以

  • 分隔符号.join(iteator)
  • iteator,迭代器可以是各种带条件的

这篇关于【python基础学习2】python里和可迭代对象iterator相关的函数:zip(), map(), join() 函数和strip()方法等的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/742401

相关文章

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Python Websockets库的使用指南

《PythonWebsockets库的使用指南》pythonwebsockets库是一个用于创建WebSocket服务器和客户端的Python库,它提供了一种简单的方式来实现实时通信,支持异步和同步... 目录一、WebSocket 简介二、python 的 websockets 库安装三、完整代码示例1.

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法