2015-04-19 121 views
3

我有一个文本文件,它看起来像这样:字符串列表

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 \\\ 

我想的对数加载到一个列表或字典。

这是我的代码至今:

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 

但是,这是错误我得到:

"while(data2[i] != ''): string out of range" 
+4

我想你是从C背景! Python中没有字符串不会以'None'结尾。没有无字符。你在Python中以字符串的形式运行循环:'for string_var中的c_var:'不在循环中使用'c_var' –

+0

你的代码的输出应该是什么样的? – ZdaR

+0

@GrijeshChauhan你对C背景是正确的。 – Lior

回答

1

这里是一个解决方案就是有点类似C的少,看起来更像蟒蛇。而不知道究竟的输出应该看起来像,第一猜测导致我这样的解决方案:

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 

这是输出:

[(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')] 

注意,这是缺少错误处理,所以如果文件不符合你的格式,这可能会引发异常。

+0

谢谢,但仍然有一个错误 > result [int(elements [Integer(0)]) ] =元素[Integer(1)] > IndexError:列表索引超出范围 – Lior

0

我想你想用i < len(data2)这样的东西代替data2[i] != ''data2[i] != None:

此外,您的代码将在该行上失败L.append((int(a),int(b))),因为221/73不是有效的文字。

2

你差不多已经有了,就像提到@Vor一样,你的条件陈述就是问题所在。文本文件不以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 

这种方法会输出一个元组列表,你问:

>>> 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')] 

注:在你的第三个最后一行,当你追加到L,您在b使用int()变量。由于该字符串的格式为'221/73',因此它不是有效的整数。你可以将字符串和int()分开,但是它会将数字分开,这可能不是你想要的。

+0

有一个错误: ValueError:需要多个值才能在 中解压a,b = line.split('&') – Lior

+1

@ Lior在像这样的字符串上使用split('&')''3&221/73“'时,有两个值可以解压缩,'3'和'221/73'。你确定你的文本文件格式正确吗? – logic

+1

@Lior:只有当数据行(反斜杠删除后)与'string1&string2'格式不匹配时,才会出现该错误消息。 –