2016-10-16 16 views
1

で長さが異なる行からリストを作成する:が、私はこのようになります私のデータのpythonで各列のリストを作成しようとしていますのpython

399.75833  561.572000000  399.75833  561.572000000 a_Fe I 399.73920 nm 
399.78316  523.227000000  399.78316  523.227000000 
399.80799  455.923000000  399.80799  455.923000000 a_Fe I 401.45340 nm 
399.83282  389.436000000  399.83282  389.436000000 
399.85765  289.804000000  399.85765  289.804000000 

問題は、私のデータの各行がAであるということです異なる長さ。とにかく、短い行の残りのスペースをスペースでフォーマットして、同じ長さになるようにしますか?

私は形であることに私のデータを希望:

list one= [399.75833, 399.78316, 399.80799, 399.83282, 399.85765] 
list two= [561.572000000, 523.227000000, 455.923000000, 389.436000000, 289.804000000] 
list three= [a_Fe, " ", a_Fe, " ", " "] 

これは私のpythonにデータをインポートするために使用するコードです:

fh = open('help.bsp').read() 
the_list = [] 
for line in fh.split('\n'): 
    print line.strip() 
    splits = line.split() 
    if len(splits) ==1 and splits[0]== line.strip(): 
     splits = line.strip().split(',') 
    if splits:the_list.append(splits) 

答えて

1

あなたのを作るためにizip_longestを使用する必要があります標準のzipは配列の指定されたリストの中で最短の長さまでしか実行されないので、

from itertools import izip_longest 
with open('workfile', 'r') as f: 
    fh = f.readlines() 

# Process all the rows line by line 
rows = [line.strip().split() for line in fh] 
# Use izip_longest to get all columns, with None's filled in blank spots 
cols = [col for col in izip_longest(*rows)] 
# Then run your type conversions for your final data lists 
list_one = [float(i) for i in cols[2]] 
list_two = [float(i) for i in cols[3]] 
# Since you want " " instead of None for blanks 
list_three = [i if i else " " for i in cols[4]] 

出力:だから

>>> print list_one 
[399.75833, 399.78316, 399.80799, 399.83282, 399.85765] 
>>> print list_two 
[561.572, 523.227, 455.923, 389.436, 289.804] 
>>> print list_three 
['a_Fe', ' ', 'a_Fe', ' ', ' '] 
0

、あなたの行は空白区切りまたはカンマ区切りのいずれかであり、そしてカンマ区切り場合、行には空白が含まれていませんか? (len(splits)==1が真であれば、splits[0]==line.strip()も真です)。それはあなたが示しているデータではなく、あなたが何を記述しているかではありません。

あなたが示したデータから、必要なリストを取得するには:あなたは、カンマ区切り(または同様に区切られた)を読んでいる場合は

with open('help.bsp') as h: 
    the_list = [ line.strip().split() for line in h.readlines() ] 
list_one = [ d[0] for d in the_list ] 
list_two = [ d[1] for d in the_list ] 
list_three = [ d[4] if len(d) > 4 else ' ' for d in the_list ] 

ファイル、私はいつもcsvモジュールを使用することをお勧め - それはたくさんの扱いあなたが考慮していない可能性のあるエッジケース。

関連する問題