简体   繁体   English

从文件到列表中的元组的字符串

[英]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"  

You almost had it, like @Vor mentioned, your conditional statements were the issue. 你几乎拥有它,就像@Vor提到的那样,你的条件陈述是个问题。 Text files don't end with None in Python so you can't do data2[i] != '' and data2[i] != None: . Python中的文本文件不以None结尾,因此您无法执行data2[i] != ''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. 注意:在第3行的最后一行中,当您附加到L ,在b变量上使用int() Since the string is in the form of '221/73' , its not a valid integer. 由于字符串的形式为'221/73' ,因此它不是有效的整数。 You could split the string and int() each individual number, but then it would divide the numbers, which is probably not what you want. 你可以拆分字符串和int()每个单独的数字,但然后它会划分数字,这可能不是你想要的。

Here is a solution that is a bit less C-like and looks more like python. 这是一个类似于C的解决方案,看起来更像python。 Without being sure what exactly the output is supposed to look like, a first guess lead me to this solution: 不确定输出应该是什么样子,第一个猜测引导我找到这个解决方案:

result = []

with open("test.txt") as f:
    lines = f.readlines()
    for l in lines:
            l = l.replace('\\', '')
            elements = l.split("&")
            elements = [x.strip() for x in elements]
            result.append((int(elements[0]), elements[1]))

print result

This is the output: 这是输出:

[(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 that this is missing error handling, so if the file does not conform to your format, this will probably throw an exception. 请注意,这是缺少错误处理,因此如果文件不符合您的格式,这可能会引发异常。

I think you want to replace data2[i] != '' and data2[i] != None: with something like this i < len(data2) . 我想你要替换data2[i] != ''data2[i] != None:用这样的东西i < len(data2)

Also your code will fail on that line L.append((int(a),int(b))) because 221/73 is not a valid literal. 此外,您的代码将在该行上失败L.append((int(a),int(b)))因为221/73不是有效的文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM