Creating lists from rows with different lengths in python
<p>I am trying to create a list for each column in python of my data that looks like this:</p>

<pre><code>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  
</code></pre>

<p>The problem is that each row of my data is a different length. Is there anyway to format the remaining spaces of the shorter rows with a space so they are all the same length?</p>

<p>I would like my data to be in the form: </p>

<pre><code>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, " ", " "]
</code></pre>

<p>This is the code I used to import the data into python:</p>

<pre><code>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)
</code></pre>

<p>You need to use <code>izip_longest</code> to make your column lists, since standard <code>zip</code> will only run till the shortest length in the given list of arrays.</p>

<pre><code>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]]
</code></pre>

<p>Output:</p>

<pre><code>&gt;&gt;&gt; print list_one
[399.75833, 399.78316, 399.80799, 399.83282, 399.85765]
&gt;&gt;&gt; print list_two
[561.572, 523.227, 455.923, 389.436, 289.804]
&gt;&gt;&gt; print list_three
['a_Fe', ' ', 'a_Fe', ' ', ' ']
</code></pre>

python