Python内置函数--iter()&next()

前言

iter():此函数获取一个对象并返回与该参数对应的迭代器对象。
next():此函数使用迭代器并返回输入中的下一个元素。如果我们再次调用它,它会记住之前返回的值并输出下一个值。

看到了迭代器对象,那么就不得不看看魔术方法__iter__()了。只要内置有__iter__()方法的就可以称之为可迭代对象。可以转换为迭代器的对象,就称之为可迭代对象。

list_ = [1,2,3,4]
tuple_ = (1,2,3,4)
dict_ = {"name1":"清安","name2":"拾贰"}
list_.__iter__()
tuple_.__iter__()
dict_.__iter__()

列举了三个数据结构,都带有__iter__()方法。所以:

list_ = [1,2,3,4]
list_res = list_.__iter__()
print(list_res)
"""<list_iterator object at 0x0000029DF0C9FEE0>"""

这个列表也就成功变成了一个迭代器。

iter()与iter()有什么关系?

def iter(source, sentinel=None): # known special case of iter
    """
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
    """
    pass	
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

本质作用都是一样的。将可迭代对象转为迭代器对象。所以可以这样写:

list_ = [1,2,3,4]
tuple_ = (1,2,3,4)
list_res = list_.__iter__()
print(list_res)
print(iter(tuple_))
"""
<list_iterator object at 0x000001FE485CFEE0>
<tuple_iterator object at 0x000001FE485CFEB0>
"""

取值问题

list_ = [1,2,3,4]
print(next(list_))

这样会告诉你:TypeError: ‘list’ object is not an iterator,类型错误,列表对象不是迭代器。所以要想使用next()取值就必须先iter()。

list_ = [1,2,3,4]
res_list = iter(list_)
print(next(res_list))
print(next(res_list))
print(next(res_list))
print(next(res_list))
print(next(res_list))

取一次值就next一次,下一次使用next会接着上一次的位置取值。当超出后会告诉你:StopIteration停止迭代。

next()与next()有什么关系?

def next(iterator, default=None): # real signature unknown; restored from __doc__
    """
    next(iterator[, default])
    
    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.
    """
    pass
list_ = [1,2,3,4]
res_list = iter(list_)
print(next(res_list))
print(res_list.__next__())

本质作用都是一样的,迭代取值。

while与for

迭代器就是一个重复取值的工具。那么while,for似乎都是类似的作用。

list_ = [1,2,3,4]
res_list = iter(list_)
while True:
    print(next(res_list))

这样就简化了每次都要写next的情况。但是依旧会抛出异常StopIteration。

list_ = [1,2,3,4]
for value in iter(list_):
    print(value)

而for循环却不会。要想while不抛出异常我们可以用try来捕捉异常达到预期的效果。至于for循环:
![image.png](https://img-blog.csdnimg.cn/img_convert/58efc5740034be43ed5dbff5980e11ef.png#clientId=u25d924cf-3874-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=93&id=udffac118&margin=[object Object]&name=image.png&originHeight=116&originWidth=632&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11571&status=done&style=none&taskId=uf691c7c6-ee1e-458c-9bf6-e53b308c25f&title=&width=505.6)
看到了吗,for循环本质就是使用了iter,所以即使不使用iter()直接使用for value in list_也是可以的。为什么不抛出异常,应为for循环以及帮我们做了对应的操作了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 以下是 Python3 内置函数的完整列表: - abs() - all() - any() - ascii() - bin() - bool() - breakpoint() - bytearray() - bytes() - callable() - chr() - classmethod() - compile() - complex() - delattr() - dict() - dir() - divmod() - enumerate() - eval() - exec() - filter() - float() - format() - frozenset() - getattr() - globals() - hasattr() - hash() - help() - hex() - id() - input() - int() - isinstance() - issubclass() - iter() - len() - list() - locals() - map() - max() - memoryview() - min() - next() - object() - oct() - open() - ord() - pow() - print() - property() - range() - repr() - reversed() - round() - set() - setattr() - slice() - sorted() - staticmethod() - str() - sum() - super() - tuple() - type() - vars() - zip() 除此之外,还有一些 Python 内置模块,例如 `math`,`datetime`,等等也包含很多有用的函数。 ### 回答2: Python内置函数是指在Python编程语言中已经定义好的、可以直接使用的函数。以下是Python内置函数的大全表: 数值处理函数: - abs():返回一个数的绝对值。 - divmod():将两个数相除并返回商和余数。 - pow():返回一个数的指定次幂。 - round():将一个数四舍五入到指定的小数位数。 字符串处理函数: - len():返回字符串长度。 - str():将数值转换为字符串。 - format():格式化字符串。 - split():将字符串按照指定的分隔符切片成列表。 列表处理函数: - len():返回列表长度。 - max():返回列表中的最大值。 - min():返回列表中的最小值。 - sum():返回列表中所有元素的和。 字典处理函数: - len():返回字典中键值对的数量。 - keys():返回字典中所有的键。 - values():返回字典中所有的值。 - items():返回字典中所有的键值对。 文件处理函数: - open():打开一个文件并返回文件对象。 - write():向文件中写入内容。 - read():从文件中读取内容。 - close():关闭文件。 其他常用函数: - type():返回对象的类型。 - range():生成一个指定范围的整数序列。 - print():打印输出内容到控制台。 - input():接收控制台输入。 以上是一些常见的Python内置函数,可以在Python的官方文档中找到完整的内置函数列表。 ### 回答3: Python是一种功能强大的编程语言,拥有丰富的内置函数,用于完成各种任务。以下是Python内置函数大全表: 1. 数学函数:比如abs()用于取绝对值,sum()用于求和,pow()用于幂运算等。 2. 字符串函数:比如len()用于计算字符串的长度,str()用于将其他类型转换为字符串,upper()用于将字符串转换为大写等。 3. 列表函数:比如len()用于计算列表的长度,max()用于找出列表中的最大值,sorted()用于对列表进行排序等。 4. 字典函数:比如len()用于计算字典中键值对的个数,keys()用于获取字典中所有的键,values()用于获取字典中所有的值等。 5. 文件函数:比如open()用于打开文件,read()用于读取文件内容,write()用于向文件写入内容等。 6. 类型转换函数:比如int()用于将其他类型转换为整数,float()用于将其他类型转换为浮点数,str()用于将其他类型转换为字符串等。 7. 输入输出函数:比如input()用于获取用户输入内容,print()用于输出内容到控制台。 8. 布尔函数:比如bool()用于将其他类型转换为布尔值,isinstance()用于判断一个对象的类型等。 9. 时间函数:比如time()用于获取当前时间戳,sleep()用于暂停脚本的执行一段时间等。 10. 迭代器函数:比如iter()用于创建一个迭代器对象,next()用于获取迭代器的下一个值等。 以上仅列举了一部分Python内置函数,还有很多其他函数可以根据需要进行查阅。这些内置函数Python编程的基础,掌握它们能够帮助我们更高效地完成各种任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清安无别事

慢慢的积累一杯奶茶吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值