[英]How do I convert a text file into a list then sort it with Python?
[英]How do I convert a text file to a list in python?
我當前的文本文件如下所示:
1DEC S1 1 2.192 2.811 1.924
2DEC S1 4 3.686 3.143 3.151
3DEC S1 7 3.622 2.211 3.252
4DEC S1 10 3.697 3.401 2.558
5DEC S1 13 1.921 2.136 2.711
等等
我想將其轉換為僅在每行中包含最后3個數字的列表,例如:
[2.192, 2.811, 1.924, 3.686, 3.143, 3.151, 3.622, 2.211, 3.252, 3.697, 3.401 2.558, 1.921, 2.136, 2.711]
謝謝!
Numpy有一個簡單的方法。
import numpy as np
a,b = np.loadtxt('FILE LOCATION',usecols=('Column Number with 0 being
first', unpack=True)
在這種情況下,a和b應該分別為您提供各列的列表。 例如,如果要使用第4列或第5列,則可以說usecols =(5,6)等,依此類推。 由於您不需要包含字符串的列,因此不需要其他步驟。
這是一個使用list-comprehension
班輪:
with open('test.txt.', 'r') as f:
print [float(x) for line in f for x in line.split()[3:]]
輸出:
[2.192, 2.811, 1.924, 3.686, 3.143, 3.151, 3.622, 2.211, 3.252, 3.697, 3.401, 2.558, 1.921, 2.136, 2.711]
您可以嘗試以下方法:
from itertools import chain
f = open('filename.txt').readlines()
f = [i.strip('\n').split() for i in f]
new_vals = list(chain(*[map(float, i[3:]) for i in f]))
輸出:
[2.192, 2.811, 1.924, 3.686, 3.143, 3.151, 3.622, 2.211, 3.252, 3.697, 3.401, 2.558, 1.921, 2.136, 2.711]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.