[英]File handling in Python
我是python noob,我陷入了一個問題。
filehandler = open("data.txt", "r")
alist = filehandler.readlines()
def insertionSort(alist):
for line in alist:
line = list(map(int, line.split()))
print(line)
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
print(line)
insertionSort(alist)
for line in alist:
print line
輸出:
[4, 19, 2, 5, 11]
[4, 2, 5, 11, 19]
[8, 1, 2, 3, 4, 5, 6, 1, 2]
[8, 1, 1, 2, 2, 3, 4, 5, 6]
4 19 2 5 11
8 1 2 3 4 5 6 1 2
我應該對文件中的值行進行排序。 該行中的第一個值表示要排序的值的數量。 我應該按排序的順序顯示文件中的值。
insertSort中的打印調用僅用於調試目的。
輸出的前四行顯示插入排序似乎在起作用。 我不知道為什么在調用insertSort后打印列表時,這些值未排序。
我是Stack Overflow和Python的新手,所以如果這個問題放錯了位置,請告訴我。
for line in alist:
line = list(map(int, line.split()))
line
以"4 19 2 5 11"
開頭。 您將其拆分並轉換為int,即[4, 19, 2, 5, 11]
。
然后,指定這個新的價值list
-但list
是一個局部變量,新的值永遠不會被存儲回alist
。
同樣, list
是一個糟糕的變量名,因為已經有一個list
數據類型(變量名將使您無法使用該數據類型)。
讓我們重新組織程序:
def load_file(fname):
with open(fname) as inf:
# -> list of list of int
data = [[int(i) for i in line.split()] for line in inf]
return data
def insertion_sort(row):
# `row` is a list of int
#
# your sorting code goes here
#
return row
def save_file(fname, data):
with open(fname, "w") as outf:
# list of list of int -> list of str
lines = [" ".join(str(i) for i in row) for row in data]
outf.write("\n".join(lines))
def main():
data = load_file("data.txt")
data = [insertion_sort(row) for row in data]
save_file("sorted_data.txt", data)
if __name__ == "__main__":
main()
實際上,使用您的數據-每行中的第一個數字實際上不是要排序的數據-您最好這樣做
data = [row[:1] + insertion_sort(row[1:]) for row in data]
使得邏輯insertion_sort
是清潔器。
如上面的@Barmar所述,您沒有修改函數的輸入。 您可以執行以下操作:
def insertionSort(alist):
blist = []
for line in alist:
line = list(map(int, line.split()))
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
blist.append(line)
return blist
blist = insertionSort(alist)
print(blist)
另外,修改alist
“就地”:
def insertionSort(alist):
for k, line in enumerate(alist):
line = list(map(int, line.split()))
for index in range(2, len(line)):
currentvalue = line[index]
position = index
while position>1 and line[position-1]>currentvalue:
line[position]=line[position-1]
position = position-1
line[position]=currentvalue
alist[k] = line
insertionSort(alist)
print(alist)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.