为什么不能在打印后从枚举数据集创建字典?
Why can you not create a dictionary from an enumerated data set after you print it?
我在练习 enumerate()
和 python 中的词典。当我不打印枚举数据时,我可以根据枚举数据创建字典。但是当我打印出枚举数据时,我无法再创建字典。为什么会这样?
当我没有打印出我的枚举数据时:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
我的输出是
Data Dict: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Should be 'a': a
但当我不这样做时:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
for enum, point in enum_data:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
我得到:
Count: 1 Element: a
Count: 2 Element: b
Count: 3 Element: c
Count: 4 Element: d
Data Dict: {}
Should be 'a': None
enumerate
returns an iterator. An iterator may only be iterated over once.
一个常见的解决方案是使用itertools.tee
到return任意数量的独立迭代器:
from itertools import tee
data = ['a','b','c','d']
enum_data1, enum_data2 = tee(enumerate(data, 1), 2)
for enum, point in enum_data1:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data2)
print("Data Dict: ", data_dict) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
print("Should be 'a': ", data_dict.get(1)) # a
我在练习 enumerate()
和 python 中的词典。当我不打印枚举数据时,我可以根据枚举数据创建字典。但是当我打印出枚举数据时,我无法再创建字典。为什么会这样?
当我没有打印出我的枚举数据时:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
我的输出是
Data Dict: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Should be 'a': a
但当我不这样做时:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
for enum, point in enum_data:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
我得到:
Count: 1 Element: a
Count: 2 Element: b
Count: 3 Element: c
Count: 4 Element: d
Data Dict: {}
Should be 'a': None
enumerate
returns an iterator. An iterator may only be iterated over once.
一个常见的解决方案是使用itertools.tee
到return任意数量的独立迭代器:
from itertools import tee
data = ['a','b','c','d']
enum_data1, enum_data2 = tee(enumerate(data, 1), 2)
for enum, point in enum_data1:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data2)
print("Data Dict: ", data_dict) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
print("Should be 'a': ", data_dict.get(1)) # a