【问题标题】:'map' object is not subscriptable,How to extract a part of map“地图”对象不可下标,如何提取地图的一部分
【发布时间】:2022-01-16 18:40:39
【问题描述】:
     66         test_indexes = set(random.sample(indexes, len(indexes)//2)) # removing 50% edges from test data
     67         train_indexes = set(indexes).difference(test_indexes)
---> 68         test_list = [edge_list[i] for i in test_indexes]
     69         train_list = [edge_list[i] for i in train_indexes]
     70         return train_list,test_list

TypeError: 'map' 对象不可下标

我想知道如何将 edgelist(这是一个地图)的一部分放入 test_list>请帮我解决这个问题

【问题讨论】:

  • 请发布完整的可运行代码,包括示例输入

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

所以我相信,根据这些信息,您可能曾尝试通过使用 map 将函数映射到另一个列表来创建列表 (edge_list)。请以以下为例。

lst = [1,2,3]
new_lst = map(lambda x: x**2, lst)
type(new_lst)

这将返回一个不可迭代的“地图”对象。尝试将本例中的 new_lst 和你的 edge_list 转换为一个列表:

lst = [1,2,3]
new_lst = list(map(lambda x: x**2, lst))
type(new_lst)

【讨论】:

  • edge_list 使用以下代码完成:
  • edge_list = map(lambda x: tuple(map(int, x.split())), data_file.read().split("\n")[:-1])跨度>
  • 在这种情况下是的,问题是 edge_list 的类型是“地图”,而不是您期望的列表。如我所示,将地图对象投射到列表中应该可以解决问题!
  • test_list = list(map([edge_list[i] for i in test_indexes])) train_list = list(map([edge_list[i] for i in train_indexes]))
  • 是的,因为这仍然不正确,您需要按照我的回答在分配 edge_list 时执行此操作: edge_list = list(map(lambda x: tuple(map(int, x.split()) ), data_file.read().split("\n")[:-1])) 一旦edge_list的类型是list,你的train和test list的分配就可以了。
猜你喜欢
  • 2020-09-21
  • 2011-10-11
  • 1970-01-01
  • 2018-08-27
  • 2021-11-23
  • 2021-06-18
  • 2018-07-31
  • 2012-04-30
  • 1970-01-01
相关资源
最近更新 更多