什么样的对象在python中枚举返回?(What kind of objects does enumerate returns in python?)

编程入门 行业动态 更新时间:2024-10-12 16:26:33
什么样的对象在python中枚举返回?(What kind of objects does enumerate returns in python?)

我正在阅读python cookbook,它提到enumerate()返回一个迭代器,产生表单的所有对(两个元组)(index,item)

我可以使用d = dict(枚举(L))来制作一个词典。

根据我的理解,我认为enumerate()返回一个元组。 并且dict()可以将元组变成dict。

所以我尝试过:

dict((1,2))

弹出TypeError。

所以我想知道枚举什么对象实际返回到哪个dict()可以使它成为一个字典?

I'm reading python cookbook, it mentioned that enumerate() returns an iterator yielding all the pairs(two -item tuples) of the form(index, item)

And I can use d=dict(enumerate(L)) to make a dict.

For my understanding, I thought enumerate() returns a tuple. And dict() can make a tuple into dict.

So I tried:

dict((1,2))

TypeError pops out.

So I'm wondering what object did enumerate actually returns here which dict() can make it into a dict?

最满意答案

dict()构造函数接受一个iterable的key,value对序列。

您的代码段dict((1,2))无效,因为您传递的是元组(1,2) ,一个key,value对。 它迭代(1,2)并在期望序列的同时找到整数。

相反,你应该传递一个包含一对的元组:

>>> dict(((1,2),)) {1: 2}

或者,例如,列表:

>>> dict([[1,2]]) {1: 2}

enumerate()返回一个enumerate对象,它是元组对序列的迭代器:

>>> enumerate(range(10)) <enumerate object at 0x1059b0f50> >>> list(enumerate(range(10))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

希望能让你更清楚。

dict() constructor accepts an iterable sequence of key,value pairs.

Your snippet dict((1,2)) is not working because you are passing a tuple (1,2), one key,value pair. It iterates over (1,2) and finds integers while expecting sequences.

Instead you should have passed a tuple containing one pair:

>>> dict(((1,2),)) {1: 2}

Or, for example, a list:

>>> dict([[1,2]]) {1: 2}

enumerate() returns an enumerate object, which is an iterator over sequence of tuple pairs:

>>> enumerate(range(10)) <enumerate object at 0x1059b0f50> >>> list(enumerate(range(10))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

Hope that makes things more clear to you.

更多推荐

本文发布于:2023-07-26 06:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1271974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   python   kind   returns   enumerate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!