所以我寫了一個函式來分析一個文本檔案并將文本作為一個串列回傳,不包括幾個字符 ('\n',' ','!','.','@','#')
我嘗試撰寫我的代碼并使用了一個示例文本檔案filename,上面寫著I love Computer Science sooooooooooooooo much!!!!!
現在我希望我的輸出看起來像這樣......
['I', 'l', 'o', 'v', 'e', 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r', 'S', 'c', 'i', 'e', 'n', 'c', 'e', 's', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'm', 'u', 'c', 'h']
但我的輸出回傳
['I', 'l', 'o', 'v', 'e', 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r', 'S', 'c', 'i', 'e', 'n', 'c', 'e', 's', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'm', 'u', 'c', 'h', '!', '!']
但是我的代碼被編程為'!'在最后洗掉這兩個......
我應該在我的代碼中更改什么???
這是我的代碼順便說一句...
def reverse(filename):
s = open(filename, 'r')
content = s.read()
g = list(content)
for x in g:
if x in ('\n',' ','!','.','@','#'):
g.remove(x)
return g
uj5u.com熱心網友回復:
在遍歷串列時不能修改串列。好吧,你可以,但它會把迭代器指標搞砸。正確的答案是創建一個包含您要保留的內容的新串列。并且您不必為了迭代其內容而將檔案轉換為串列。字串是可迭代的,就像串列一樣。
def reverse(filename):
s = open(filename, 'r')
g = []
for c in s.read():
if c not in '\n !.@#':
g.append(c)
return g
或者:
def reverse(filename):
s = open(filename, 'r')
return [c for c in s.read() if c not in '\n !.#@']
uj5u.com熱心網友回復:
從同一串列中洗掉專案時無法迭代串列,因為索引已更改,因此最好的方法是以相反的順序迭代串列
看到解決辦法是:
def reverse(filename):
s = open(filename, 'r')
content = s.read()
g = list(content)
for x in reversed(g):
if x in ('\n',' ','!','.','@','#'):
g.remove(x)
return g
輸出 :
['I','l','o','v','e','C','o','m','p','u','t','e','r','S','c','i','e','n','c','e','s','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','m', 'u','c','h']
uj5u.com熱心網友回復:
正如蒂姆的回答所說,處理這個問題的原則方法是創建一個包含你想要保留的東西的新串列。也就是說,您可能會發現有趣的是,如果向后遍歷串列,從技術上講可以從串列中洗掉專案而不會弄亂迭代器指標。
話雖如此,這里是對您的代碼的修改,它不會生成單獨的串列。
def reverse(filename):
s = open(filename, 'r')
content = s.read()
g = list(content)
for k in range(len(g))[::-1]:
if g[k] in ('\n',' ','!','.','@','#'):
g.pop(k)
return g
請注意,與“洗掉”功能不同,“彈出”功能在實作時不需要搜索串列。
或者,只要您使用“remove”函式,您就可以使用remove 函式搜索串列的事實來避免“從頭開始”搜索串列。考慮以下:
def reverse(filename):
s = open(filename, 'r')
content = s.read()
g = list(content)
for c in ('\n',' ','!','.','@','#'):
while c in g:
g.remove(c)
return g
值得注意的是,對c in gwhile 條件的檢查包括一個額外的搜索。我們可以通過在找不到字符的情況下處理 remove 函式的例外來避免這種情況。
def reverse(filename):
s = open(filename, 'r')
content = s.read()
g = list(content)
for c in ('\n',' ','!','.','@','#'):
while True:
try:
g.remove(c)
except(ValueError):
break
return g
uj5u.com熱心網友回復:
洗掉可能更有效str.replace:
def reverse(filename):
with open(filename) as f:
s = f.read()
for c in '\n !.@#':
s = s.replace(c, '')
return list(s)
這會遍歷字串幾次,但這種字串方法非常快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401104.html
