Python:将地图对象转换为列表会使地图对象为空?
我有一个地图对象,我想将其打印为列表,但此后继续用作地图对象。其实我想打印长度以便转换为列表,但是如果我仅按如下方式打印内容,也会出现此问题:
I have a map object that I want to print as a list but continue using as a map object afterwards. Actually I want to print the length so I cast to list but the issue also happens if I just print the contents as follows:
print("1",my_map)
print("1",list(my_map))
print("2",my_map)
print("2",list(my_map))
这给了我以下输出。
1 <map object at 0x7fd2962a75f8>
1 [(1000.0, 1.0, 0.01, 0.01, 0.01, 0.01, 0.01)]
2 <map object at 0x7fd2962a75f8>
2 []
为什么会发生这种情况,以及如何避免继续使用地图及其内容?
Why is this happening and how can I avoid it to continue using the map and its contents?
map
对象是返回的生成器调用 map()
内置功能。它打算仅迭代一次(例如,将其传递到 list()
),然后再使用。尝试对其进行第二次迭代将导致序列为空。
A map
object is a generator returned from calling the map()
built-in function. It is intended to be iterated over (e.g. by passing it to list()
) only once, after which it is consumed. Trying to iterate over it a second time will result in an empty sequence.
如果要保存映射的值以供重用,则需要转换 map
对象映射到另一个序列类型,例如 list
,然后保存结果。因此,请更改您的内容:
If you want to save the mapped values to reuse, you'll need to convert the map
object to another sequence type, such as a list
, and save the result. So change your:
my_map = map(...)
至
my_map = list(map(...))
之后,上面的代码应该可以按预期工作。
After that, your code above should work as you expect.