如何在一行中解析元组数据

时间:2015-04-09 21:25:35

标签: python python-3.x

我必须将用户输入放在以下格式的一行中:

C = (39.447; 94.657; 11.824) N = (39.292; 95.716; 11.027) Ca = (39.462; 97.101; 11.465)

我必须翻译它,所以我有三个变量,每个变量对应于适当的元组。半冒号和它必须在一条线上的事实使这变得复杂。

这是我到目前为止,但是我将它解析为一行时,我认为eval()可能有效,因为输入类似于变量赋值但我得到“SyntaxError无法分配给文字”。我觉得应该有一个简单的方法来做到这一点。

class TupleClean(str):
    def clean(self):
        new_list = []
        clean_coord = self.strip("() ")
        split_coord = clean_coord.split(";")
        for i in split_coord:
            new_list.append(float(i))
        tuple_coord = (new_list[0], new_list[1], new_list[2])
        return(tuple_coord)

coord_1 = input("Input the coordinates for carbon in the format (p; q; r): ")
coord_2 = input("Input the coordinates for nitrogen in the format (p; q; r): ")
coord_3 = input("Input the coordinates for calcium in the format (p; q; r): ")

coord_1_clean = TupleClean(coord_1)
coord_1_clean = coord_1_clean.clean()
coord_2_clean = TupleClean(coord_2)
coord_2_clean = coord_2_clean.clean()
coord_3_clean = TupleClean(coord_3)
coord_3_clean = coord_3_clean.clean()

4 个答案:

答案 0 :(得分:0)

tuple类的构造函数可以将iterable作为参数:

class TupleClean(str):
    def clean(self):
        new_list = []
        clean_coord = self.strip("() ")
        return tuple(map(float, clean_coord.split(";")))

(map将函数float应用于列表clean_coord.split(";"))的每个项目

答案 1 :(得分:0)

如果输入格式始终相同,为什么不使用带捕获组的正则表达式,然后只需将捕获的组转换为浮点数并将它们作为三个元组分配给三个变量?

答案 2 :(得分:0)

使用正则表达式,您可以在一个单独的输入中创建一个字典data,如下所示:

import re

regex = r'(\w+) = \(([\d.]+); ([\d.]+); ([\d.]+)\)'
data = re.findall(regex, input('Enter all data: '))
data = {i[0]:[float(j) for j in i[1:]] for i in data}

答案 3 :(得分:0)

我认为将str子类化为解析字符串有点不寻常。我建议你使用正则表达式解析。

COORDINATES_REGEX = re.compile(r'^\(([\d.]+);\s([\d.]+);\s([\d.]+)\)$')
match = COORDINATES_REGEX.match(coords_1)
if match is None:
     raise ValueError("Invalid input")
coords = tuple(map(float, match.groups()))