【问题标题】:Python is it possible to store tuple coordinates in a nested dict and access a single coordinate from a single dict within the nested dict?Python是否可以将元组坐标存储在嵌套字典中并从嵌套字典中的单个字典访问单个坐标?
【发布时间】:2020-07-06 09:42:57
【问题描述】:

我有一些代码使用字典来存储坐标值。我更喜欢有一个键'R1N1'的东西,值是x和y坐标的元组,但我不知道这在python中是否可行,或者你如何为它的任何一个索引键元组x 或 y 分量:

代码

import json

rnID = dict ([
('R1N1x', 1),
('R1N1y', 111),
('R1N500x', 222),
('R1N500y', 222),
('R2N1x', 1),
('R2N1y', 111),
('R2N500x', 222),
('R2N500y', 222)
])

with open('rnID.txt', 'w') as outfile:
    json.dump(rnID, outfile)

这适用于存储坐标,但有点冗长。

期望的输出

something like 
new_dict = {[
('R1N1',(1,111))
...

【问题讨论】:

  • 为什么不存储{'R1N1': {'x': 1, 'y': 111}, ... }这样的坐标?
  • 谢谢@MjZac 你会如何读取和写入字典元组?
  • 你会如何存储一个坐标?然后,您用来执行此操作的东西将成为您想要的 dict 中的一个值。我真的认为你想多了。

标签: python dictionary nested tuples cartesian-coordinates


【解决方案1】:

给你:

rns = {}
for k, v in rnID.items():   
    part = k[-1]
    k = k[:-1]
    if k not in rns:
        rns[k] = [0, 0]
    rns[k][0 if part == 'x' else 1] = v

print(rns)

输出

{'R1N1': [1, 111], 'R1N500': [222, 222], 'R2N1': [1, 111], 'R2N500': [222, 222]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多