Read tuples from text file

前端 未结 3 872
失恋的感觉
失恋的感觉 2021-01-14 12:39

I need to read tuples from a txt. I tried with numpy (using genfromtxt) but it didn\'t work (or at least, I don\'t know how). This is is my txt:

(0,0) (0,0)         


        
3条回答
  •  难免孤独
    2021-01-14 12:55

    Here's a simple way without using any libraries:

    tuples = []
    for t in open('input.txt').read().split():
        a, b = t.strip('()').split(',')
        tuples.append((int(a), int(b)))
    

    List comprehension equivalent:

    [tuple(int(i) for i in t.strip('()').split(',')) for t in open('input.txt').read().split()]
    


    With input.txt being the data provided in the question, this is the output:

    [(0, 0), (0, 0), (1, 0), (2, 3), (1, 0), (1, 1), (1, 1), (3, 3), (2, 0), (1, 2), (2, 1), (4, 4), (3, 0), (2, 2), (3, 1), (5, 5)]
    

提交回复
热议问题