【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

相关文章

Java对象和JSON字符串之间的转换方法(全网最清晰)

《Java对象和JSON字符串之间的转换方法(全网最清晰)》:本文主要介绍如何在Java中使用Jackson库将对象转换为JSON字符串,并提供了一个简单的工具类示例,该工具类支持基本的转换功能,... 目录前言1. 引入 Jackson 依赖2. 创建 jsON 工具类3. 使用示例转换 Java 对象为

解读为什么@Autowired在属性上被警告,在setter方法上不被警告问题

《解读为什么@Autowired在属性上被警告,在setter方法上不被警告问题》在Spring开发中,@Autowired注解常用于实现依赖注入,它可以应用于类的属性、构造器或setter方法上,然... 目录1. 为什么 @Autowired 在属性上被警告?1.1 隐式依赖注入1.2 IDE 的警告:

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

使用Python创建一个能够筛选文件的PDF合并工具

《使用Python创建一个能够筛选文件的PDF合并工具》这篇文章主要为大家详细介绍了如何使用Python创建一个能够筛选文件的PDF合并工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录背景主要功能全部代码代码解析1. 初始化 wx.Frame 窗口2. 创建工具栏3. 创建布局和界面控件4

一文详解如何在Python中使用Requests库

《一文详解如何在Python中使用Requests库》:本文主要介绍如何在Python中使用Requests库的相关资料,Requests库是Python中常用的第三方库,用于简化HTTP请求的发... 目录前言1. 安装Requests库2. 发起GET请求3. 发送带有查询参数的GET请求4. 发起PO

Python与DeepSeek的深度融合实战

《Python与DeepSeek的深度融合实战》Python作为最受欢迎的编程语言之一,以其简洁易读的语法、丰富的库和广泛的应用场景,成为了无数开发者的首选,而DeepSeek,作为人工智能领域的新星... 目录一、python与DeepSeek的结合优势二、模型训练1. 数据准备2. 模型架构与参数设置3

Python进行PDF文件拆分的示例详解

《Python进行PDF文件拆分的示例详解》在日常生活中,我们常常会遇到大型的PDF文件,难以发送,将PDF拆分成多个小文件是一个实用的解决方案,下面我们就来看看如何使用Python实现PDF文件拆分... 目录使用工具将PDF按页数拆分将PDF的每一页拆分为单独的文件将PDF按指定页数拆分根据页码范围拆分

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

Python中常用的四种取整方式分享

《Python中常用的四种取整方式分享》在数据处理和数值计算中,取整操作是非常常见的需求,Python提供了多种取整方式,本文为大家整理了四种常用的方法,希望对大家有所帮助... 目录引言向零取整(Truncate)向下取整(Floor)向上取整(Ceil)四舍五入(Round)四种取整方式的对比综合示例应

python 3.8 的anaconda下载方法

《python3.8的anaconda下载方法》本文详细介绍了如何下载和安装带有Python3.8的Anaconda发行版,包括Anaconda简介、下载步骤、安装指南以及验证安装结果,此外,还介... 目录python3.8 版本的 Anaconda 下载与安装指南一、Anaconda 简介二、下载 An