我正在阅读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.
更多推荐
发布评论