I have a file with data that I want to separate into various lists depending on the value in the first column. I know exactly what the possible values within the first column are, but they are not in any nice mathematical progression. Is there a shorter way to write the following code?
x0=[]
y0=[]
x2=[]
y2=[]
x16=[]
y16=[]
# etc.
for line in file:
words=line.split()
if words[0] == '0':
x0.append(words[1])
y0.append(words[2])
elif words[0] == '2':
x2.append(words[1])
y2.append(words[2])
elif words[0] == '16':
x16.append(words[1])
y16.append(words[2])
# etc.
My thought process is below, but the strings (x and y) that I define are obviously strings and don't refer back to the lists that I want them to refer to.
x0=[]
y0=[]
x2=[]
y2=[]
x16=[]
y16=[]
# etc
for line in file:
words=line.split()
x='x'+words[0]
y='y'+words[0]
x.append(words[1])
y.append(words[2])
Update: I realize it is possible to do this with a dictionary, where my value would be a list of lists, but mainly I'm curious if there is a pythonic way to code this that follows my train of thought as outlined above.
Use a defaultdict
instead of a bunch of individual values.
from collections import defaultdict
extracted_values = defaultdict(list)
for line in file:
words = line.split()
extracted_values['x' + words[0]].append(words[1])
extracted_values['y' + words[0]].append(words[2])
Then you'd just access your values by dictionary key instead of variable name.
extracted_values['x0']
extracted_values['y1']
I suggest that you turn
x0=[]
x2=[]
x16=[]
into a single dictionary:
x={'0':[], '2':[], '16':[]}
You can then reference the individual lists as x['0']
, x['2']
etc.
In particular, you'll be able to rewrite the for
loop like so:
for line in file:
words = line.split()
x[words[0]].append(words[1])
y[words[0]].append(words[2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With