Как назначить первый столбец в текстовом файле переменной списка? - PullRequest
0 голосов
/ 05 августа 2020

У меня есть текстовый файл с такими «строками»

5.0125,511.2,5.12.3,4.51212,45.412,54111.5142 \n
4.23,1.2,2.6,2.3,1.2,1.554 \n

Как назначить каждому столбцу отдельный список чисел с плавающей запятой? Я потратил на это несколько часов, но я заблудился.

Ожидаемые результаты

list 1 = [5.0125, 4.23]
list 2 = [511.2, 1.2 ]

Обновление: добавление пробной версии:

for line in f:
    lis = [float(line.split()[0]) for line in f]
    print("lis is ", list)


    tmp = line.strip().split(",")
    values = [float(v) for v in tmp]
    points4d = np.array(values).reshape(-1,11)  #11 is number of elements in the line
    print("points4d", points4d)
    for i in points4d:
        points3d_first_cluster = points4d[:, :3]        # HARD CODED PART
        points3d_second_cluster = points4d[:, 3:6]
        points3d_third_cluster = points4d[:, 6:9]
        #print("x_values_first_cluster",x_values_first_cluster)
    print("points3d first cluster ",points3d_first_cluster)
    print("points3d second cluster", points3d_second_cluster)
    print("points for third cluster", points3d_third_cluster)

Ответы [ 2 ]

0 голосов
/ 05 августа 2020
lists = []
with open ("text.txt", "r") as file:
    for lines in file.readlines():
        lista = [s for s in lines.split(',')]
        lista.pop(-1)
        lists.append(lista)
final_list = []
for x in range (len(lists[0])):
    i = x+1
    print("list {}".format(i))
    globals()['list%s' % i] = [lists[0][x],lists[1][x]]
    print(globals()['list%s' % i])


print(list1)


Output : 
list 1
['5.0125', '4.23']
list 2
['511.2', '1.2']
list 3
['5.12.3', '2.6']
list 4
['4.51212', '2.3']
list 5
['45.412', '1.2']
['5.0125', '4.23'] # Output of print(list1)
0 голосов
/ 05 августа 2020

это должно работать:

lists = []
with open ("text.txt", "r") as file:
    for lines in file.readlines():
        lista = [s for s in lines.split(',')]
        lista.pop(-1)
        lists.append(lista)
 final_list = []
 for x in range (len(lists[0])):
    list_new = [lists[0][x],lists[1][x]]
    final_list.append(list_new)
    print(list_new)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...