![](/img/trans.png)
[英]How to take a list of tuples and change the tuples from strings to integers
[英]Strings from files to tuples in list
我有一個看起來像這樣的文本文件:
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"
你幾乎擁有它,就像@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')]
注意:在第3行的最后一行中,當您附加到L
,在b
變量上使用int()
。 由於字符串的形式為'221/73'
,因此它不是有效的整數。 你可以拆分字符串和int()
每個單獨的數字,但然后它會划分數字,這可能不是你想要的。
這是一個類似於C的解決方案,看起來更像python。 不確定輸出應該是什么樣子,第一個猜測引導我找到這個解決方案:
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')]
請注意,這是缺少錯誤處理,因此如果文件不符合您的格式,這可能會引發異常。
我想你要替換data2[i] != ''
和data2[i] != None:
用這樣的東西i < len(data2)
。
此外,您的代碼將在該行上失敗L.append((int(a),int(b)))
因為221/73
不是有效的文字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.