返回x和y坐标元组的列表

时间:2016-05-29 22:43:19

标签: python-3.x tuples

我正在尝试在读取带有数字的文本文件后返回x和y坐标元组的列表,例如:

68,125
113,69
65,86
108,149
152,53

我已经到了这样的地步,我返回一个数字列表,但不是元组中的对。

这是我的代码:

def read_numbers(filename):
    numbers = []
    input_file = open(filename, "r")
    content = input_file.readlines()
    numbers = [word.strip() for word in content]
    input_file.close()
    return numbers
def main():
    numbers = read_numbers('output.txt')
    print(numbers)

main()

2 个答案:

答案 0 :(得分:0)

您可以读取每一行,然后用逗号分隔每一行,并使用地图将该分割的每一部分转换为int。最后将其转换为元组

coords = [tuple(map(int, line.split(","))) for line in lines]

这给出了输出:

[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53)]


您的完整代码可能如下所示:

with open("output.txt") as f:
    lines = f.readlines()

coords = [tuple(map(int, line.split(","))) for line in lines]
print(coords)

答案 1 :(得分:0)

我建议使用生成器,因为它允许您使用其他控制结构,然后列出理解:

def parse_file(file):
    for line in file:
        num1, num2 = line.split(",") #this can't be done in list comprehension
        yield (int(num1), int(num2))

然后你的read_numbers看起来像这样:

def read_numbers(filename):
    with open(filename,"r") as f:
        return list(parse_file(f))