Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using name of list as a string to access list

Tags:

python

list

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.

like image 825
user2162302 Avatar asked Dec 20 '22 08:12

user2162302


2 Answers

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']
like image 140
Silas Ray Avatar answered Feb 27 '23 00:02

Silas Ray


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])
like image 41
NPE Avatar answered Feb 27 '23 00:02

NPE