Lily Sharpton Lily Sharpton - 10 days ago 6
Python Question

python code error in mapping file values to list

I have two lists structured somehow like this:

A= [[1,27],[2,27],[3,27],[4,28],[5,29]]
B= [[6,30],[7,31],[8,31]]


and i have a file that has numbers:

1 5
2 3
3 1
4 2
5 5
6....


i want a code that reads this file and maps it to the list. e.g if the file has 1, it should read A list and output 27, if it has 6, it should read B and print 30, such that I get

27 29
27 27
27 27
28 27
29 29
30 31


The problem is, that my code gives index error, i read the file line by line and have an if condition that checks if the number i read from the file is less than the maximum number in list A, if so, it outputs the second character of that list and otherwise move on. The problem is, that instead of moving on to list B, my program still reads A and gives index error.

with open(filename) as myfile:
for line in myfile.readlines():
parts=line.split()
if parts[0]< maxnumforA:
print A[int(parts[0])-1]
else:
print B[int(parts[0]-1)

Answer

You should turn that lists into dictionaries. For example:

_A = dict(A)
_B = dict(B)

with open(filename) as myfile:
    for line in myfile:
        parts = line.split()
            for part in parts:
                part = int(part)
                if part in _A:
                    print _A[part]
                elif part in _B:
                    print _B[part]

If the action that will take place does not need to know if it comes from A or B, both can be turned into a single dictionary:

d = dict(A + B)

with open(filename) as myfile:
    for line in myfile:
        parts = line.split()
            for part in parts:
                part = int(part)
                if part in d:
                    print d[part]
Comments