简体   繁体   English

如何从odict_iterator中获取OrderedDict值?

[英]How to get OrderedDict values out of odict_iterator?

I am using the tsplib95 to parse .tsp files. 我正在使用tsplib95解析.tsp文件。 I want to get a list of nodes out of the Problem class from tsplib95. 我想从tsplib95中从Problem类中获取节点列表。 I checked the documentation, the get_nodes() method returns an iter() over OrderedDict of nodes. 我检查了文档,get_nodes()方法在节点的OrderedDict上返回了iter()。

How do I access the values of the OrderedDict using the iterator? 如何使用迭代器访问OrderedDict的值? I can only ever iterate over the key values using the iterator. 我只能使用迭代器迭代键值。

The OrderedDict looks like this: OrderedDict看起来像这样:
OrderedDict([(1, (20833.3333, 17100.0)), ..., (29, (27462.5, 12992.2222))]) OrderedDict([[1,(20833.3333,17100.0)),...,(29,(27462.5,12992.2222)]])

I tried getting the coordinates value in a for loop and using the next () method. 我尝试在for循环中获取坐标值并使用next ()方法。

            tsp_instance = tsplib95.load_problem(file.value)
            iterator = tsp_instance.get_nodes()

            print(next(iterator))
            print(iterator.__next__())

            for i in iterator:
                print(i)

But all of these only access the keys in the OrderedDict I do not know how to get the values of the coordinates when I do not have the original OrderedDict. 但是所有这些仅访问OrderedDict中的键,而我没有原始的OrderedDict时,我不知道如何获取坐标的值。

You will need to get a different iterator. 您将需要获得其他迭代器。 The default iterator does not know the values, only the keys. 默认迭代器不知道值,仅键。 For example 例如

>>> od = OrderedDict([('a', 1), ('b', 2)])
>>> iterator = iter(od.items())
>>> print(list(iterator))
[('a', 1), ('b', 2)]

In Python 2, you can also do iterator = od.iteritems() 在Python 2中,您还可以执行iterator = od.iteritems()

get_nodes() is not the tool you should be using for this. get_nodes()不是您应该使用的工具。 get_nodes() is only intended to return an iterator over nodes; get_nodes()仅用于在节点上返回迭代器; the fact that this iterator is sometimes an iterator over an OrderedDict is an implementation detail, and it will not always be an OrderedDict iterator. 该迭代器有时是OrderedDict上的迭代器的事实是实现细节,并且它不一定总是OrderedDict迭代器。

If you want to access the node coordinates of a problem instance that has node coordinates, you should use get_graph() and inspect the NetworkX node attributes ; 如果要访问具有节点坐标的问题实例的节点坐标,则应使用get_graph()并检查NetworkX 节点属性 the coordinates for a node will be under the 'coord' node attribute. 节点的坐标将在'coord'节点属性下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM