Python:将地图对象转换为列表会使地图对象为空? [英] Python: casting map object to list makes map object empty?

查看:90
本文介绍了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.

这篇关于Python:将地图对象转换为列表会使地图对象为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆