Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings from files to tuples in list

I have a text file that looks like this:

3 & 221/73 \\\  
4 & 963/73 \\\  
5 & 732/65 \\\  
6 & 1106/59 \\\  
7 & 647/29 \\\  
8 & 1747/49 \\\  
9 & 1923/49 \\\  
10 & 1601/41 \\\  
6 & 512 \\\

I want to load the pairs of numbers into a list or a dictionary.

This is the code I have so far:

L = []
data1 = data.replace (" \\\\", " ")
data2 = data1.replace(" & "," ")
i=0
a=''
b=''
while data2[i] != None:
    if(a==''):
        while( data2[i] != '' ):
            a=a+data2[i]
            i = i + 1
        while(data2[i] !=''):
            b=b+data2[i]
            i = i + 1
    L.append((int(a),int(b)))
    a=''
    b=''
    i=i+1

But this is the error I get:

"while( data2[i] != '' ):  string out of range"  
like image 869
Lior Avatar asked Nov 23 '25 04:11

Lior


1 Answers

You almost had it, like @Vor mentioned, your conditional statements were the issue. Text files don't end with None in Python so you can't do data2[i] != '' and data2[i] != None:.

with open("data.txt") as f:
    L=[]
    for line in f:
        line=line.replace(" \\\\\\", "").strip() #Replace \\\ and strip newlines
        a,b=line.split(' & ')                    #Split the 2 numbers
        L.append((int(a),b))                     #Append as a tuple

This approach would output a list of tuples, which you asked for:

>>> L
[(3, '221/73'), (4, '963/73'), (5, '732/65'), (6, '1106/59'), (7, '647/29'), (8, '1747/49'), (9, '1923/49'), (10, '1601/41'), (6, '512')]

Note: In your 3rd last line, when you append to L, you use int() on the b variable. Since the string is in the form of '221/73', its not a valid integer. You could split the string and int() each individual number, but then it would divide the numbers, which is probably not what you want.

like image 112
logic Avatar answered Nov 24 '25 20:11

logic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!