我有一個文件“f.txt”,其中有很多str類型的數字。每個數字最多有 9 位數字,最少有 3 位數字。每個數字都由一個新的行字符分隔(所以每個數字都在自己的行中,我不知道如何正確格式化,所以下面的例子在格式方面并不準確)。我想編寫一個循環訪問該文件的函數,并檢查該文件中是否有任何重復的數字。文件的內部如下所示:1244816 \n 2760125 \n 1102758 \n 713765 \n 6521147 \n 4711995 \n 1494276 \n 12336119 \n 8398120 \n 1215092 \n 8125139 \n ...with open("ket.txt") as f:line = f.readline()status = Truewhile status: if line == #looping through the entire file to see if there is #identical number: status = False我有一些偽代碼?我不確定如何實現評論部分。
1 回答
一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
假設我有一個包含以下內容的文件:f.txt
12324
41564
7754564654654
123
87642
123
89745312
然后下面的python腳本,我們來調用它:scan.py
def main():
with open('f.txt', 'r') as f:
numbers_seen = set()
for n in f:
if n in numbers_seen:
print('{} appears more than once!'.format(n.strip()))
return
numbers_seen.add(n)
if __name__ == '__main__':
main()
然后運行將產生:python scan.py
123 appears more than once!
添加回答
舉報
0/150
提交
取消
