Tupling浮动成对并将它们添加到python字典中

时间:2017-11-01 10:29:15

标签: python dictionary

我有一个国家/地区的文本文件,其中一些描述坐标,格式如下:

  

国家

     

57.7934235704; 24.3128625831 58.3834133979; 24.42892785 58.2573745795; 24.0611983579 58.6127534044; 23.4265600929

我无法将文件转换为以country为键的python字典,以及值为float-tuples列表的列表,如下所示:

[[(57.7934235704, 24.3128625831), (58.3834133979, 24.42892785), (58.2573745795, 24.0611983579), (58.6127534044, 23.4265600929)]]

我设法最终得到以下代码,在我的理解中,我们设法将国家/地区作为关键字添加,并单独浮动坐标,因此缺少的是一种对浮点数进行元组化的方法成对出现,并将它们添加到相应的国家/地区。

def read_country_file(filename):
with open(filename) as file:
    dict = {}
    for line in file:
        line = line.rstrip().split(' ')
        for element in line:
            if re.match('^[A-Z]', element):  #if the line starts with a letter make it a key
                country = (element[0:])
                dict[country] = country
            elif re.match('^[-0-9;. ]', element):  #if the line starts with a number make it a value
                element = element.split(';')
                for i in element:
                    flo = float(i)
                #MISSING: Tuple floats in pairs and add them to the dictionary
return dict

如果我在此词典中查找某个国家/地区,它会正确找到该国家/地区,但它没有附加值。如果我打字测试我的" flo"重视它是一个浮动,所以我有一种感觉,我几乎就在那里。

3 个答案:

答案 0 :(得分:0)

让我们使用元组理解:

element =  tuple(float(i) for i in element.split(';'))

此外,我的问题解决方案:

import re

text = ['Vietnam',
        '57.7934235704;24.3128625831 58.3834133979;24.42892785 58.2573745795;24.0611983579 58.6127534044;23.4265600929']

def get_tuples_of_float(string):
    return [tuple(map(float, j)) for j in re.findall('([\d.]+);([\d.]+)', string)] 

it = iter(text)
output = { i : get_tuples_of_float(next(it)) for i in it if re.match('^[A-Z]', i)}

答案 1 :(得分:0)

您可以使用re.findall

import re
s = """
57.7934235704;24.3128625831 58.3834133979;24.42892785 58.2573745795;24.0611983579 58.6127534044;23.4265600929
"""
new_data = map(float, re.findall('[\d\.]+', s))
final_data = {new_data[i]:new_data[i+1] for i in range(0, len(new_data), 2)}

输出:

{58.6127534044: 23.4265600929, 58.2573745795: 24.0611983579, 58.3834133979: 24.42892785, 57.7934235704: 24.3128625831}

答案 2 :(得分:0)

为什么不首先根据空格分割每行文本然后从它出来的数组,然后根据它们常用的分号拆分每个单独的坐标对,然后你就可以添加字典上的国家/地区的所有内容。