如何将枚举对象转换为python中的set和tuple?

时间:2018-02-12 15:25:34

标签: python

如何将枚举对象转换为python中的set和tuple?

grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
print(set(enumerateGrocery)) # returning set()
print(tuple(enumerateGrocery))# returning ()

Excepted output:-
{(0, 'bread'), (1, 'milk'), (2, 'butter')}
((0, 'bread'), (1, 'milk'), (2, 'butter'))

4 个答案:

答案 0 :(得分:4)

enumerate返回第一个使用者(即set构造函数)耗尽的迭代器。例如:

grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)  
print(type(enumerateGrocery))

t = tuple(enumerateGrocery)  # tuple first, to maintain order
# now, enumerateGrocery is exhausted (empty)
s = set(t)  # just use the tuple that now contains all the elements
print(s) 
print(t)

答案 1 :(得分:0)

第一个示例输出无效。无论如何:

tuple(((i,v) for i, v in enumerate(grocery)))

或者只是

tuple(enumerate(grocery))

答案 2 :(得分:0)

enumerate函数是一个生成器,这意味着你必须迭代它以从中获取项目。一个快速的方法是使用这样的集合理解:

grocery = ['bread', 'milk', 'butter']
{(i, x) for i, x in enumerate(grocery)}

答案 3 :(得分:0)

您也可以使用zip功能执行此操作:

grocery = ['bread', 'milk', 'butter']

grocerySet = set(zip(grocery,range(len(grocery))))
groceryTuple = tuple(zip(grocery,range(len(grocery))))

print(grocerySet)
print(groceryTuple)

输出:

{('milk', 1), ('butter', 2), ('bread', 0)}
(('bread', 0), ('milk', 1), ('butter', 2))