Read file as a list of tuples

前端 未结 3 1502
慢半拍i
慢半拍i 2021-02-09 09:03

I want to read a text file using Python. My list must be like this:

mylist = [(-34.968398, -6.487265), (-34.969448, -6.488250),
          (-34.967364, -6.492370)         


        
3条回答
  •  猫巷女王i
    2021-02-09 09:59

    One of the most efficient way to read delimited data like this is using numpy.genfromtxt. For example

    >>> import numpy as np
    >>> np.genfromtxt(r't3.txt', delimiter=',')
    array([[-34.968398,  -6.487265],
           [-34.969448,  -6.48825 ],
           [-34.967364,  -6.49237 ],
           [-34.965735,  -6.582322]])
    

    Otherwise you could use a list comprehension to read line by line, split on ',', convert the values to float, and finally produce a list of tuple

    with open('t3.txt') as f:
        mylist = [tuple(map(float, i.split(','))) for i in f]
    

    Note that when you open a file using with it will take care of closing itself afterwards so you don't have to.

提交回复
热议问题