Python:将多个值引用到键

时间:2017-01-27 15:43:09

标签: python dictionary

我是python的一个完整的菜鸟所以我道歉,如果我甚至没有正确地说出标题......我有一些看起来像这样的数据:

array([[   5, 9, 4, 11, -22.949, 0   ],
       [   5, 10, 3, 14, -22.454, 0   ],
          ........................
       [   4, 11, 4, 14, -21.952, 0   ]])

其中前四列是指两对地图数据。 我还有一个地图密钥,我设法将其放入字典中:

{'9': ['5', '9'],
 '10': ['5', '10'],
 ..............
 '64': ['4', '11']}

基本上我想创建一个新的文本文件,其中地图数据被字典键替换,所以:

array([[5, 9, 4, 11, -22.949, 0]]

看起来像

array([[9, 64, -22.949, 0]]

我只使用python进行绘图和一些计算(本质上是一个自动化的Excel ...)所以我很感激这个问题的任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

import csv
import operator


coords = operator.itemgetter(0,1,2,3)
with open('path/to/data.csv') as infile, open('path/to/mapkey.csv') as mapfile:
    ids = {}
    for row in csv.reader(mapfile):
        name, x, y = map(int, row)
        ids[(x,y)] = name

    answer = []
    for x,y, a,b in map(coords, csv.reader(infile)):
        answer.append([ids[(x,y)]], ids[(a,b)]])

这应该给你answer,这是一个2d列表,每个子列表中有两个映射键

相关问题