我有这个,我不知道如何返回排序列表。
def perkSort(lst):
for i in range(1, len(lst)):
number = lst[i]
j = i - 1
while (j >= 0) and (lst[j] > number):
lst[j+1] = lst[j]
j -= 1
lst[j+1] = number
def createList (x):
lst = []
lst = [num.split(',') for num in x.readlines()]
return lst
def main ():
x = open(input('Enter File Name (Example - test.txt): '))
lst = [createList (x)]
sort = perkSort(lst)
print(sort)
main ()
答案 0 :(得分:1)
与内置的Python sort()
一样,您的perkSort()
就地修改了列表,因此您无需返回它。但是,您的createList()
有点搞砸了。
我想我已经正确地猜到了test.txt文件中的数据布局。这是一个生成随机测试数据的简短程序:
import random
random.seed(42)
r = range(10)
data = '\n'.join([', '.join([str(random.randint(0,100)) for i in r]) for j in r])
with open('test.txt', 'w') as f:
f.write(data + '\n')
这是我修改过的程序版本,用于对数据进行排序:
def perkSort(lst):
for i in range(1, len(lst)):
number = lst[i]
j = i - 1
while (j >= 0) and (lst[j] > number):
lst[j+1] = lst[j]
j -= 1
lst[j+1] = number
def createList(x):
lst = []
for line in x:
lst += [int(s) for s in line.split(',')]
return lst
def main():
fname = input('Enter File Name (Example - test.txt): ')
#fname = 'test.txt'
x = open(fname, 'r')
lst = createList(x)
x.close()
print('Unsorted')
print(lst)
perkSort(lst)
print('\nSorted')
print(lst)
if __name__ == '__main__':
main()
答案 1 :(得分:0)
我不知道你在问什么。但是这里可能会对你有所帮助:
def perkSort(lst):
for i in range(1, len(lst)):
number = lst[i]
j = i - 1
while (j >= 0) and (lst[j] > number):
lst[j+1] = lst[j]
j -= 1
lst[j+1] = number
return lst #<--------------
或者你可以lst
全球:
def perkSort():
global lst
for i in range(1, len(lst)):
number = lst[i]
j = i - 1
while (j >= 0) and (lst[j] > number):
lst[j+1] = lst[j]
j -= 1
lst[j+1] = number
def createList (x):
global lst
lst = [num.split(',') for num in x.readlines()]
def main ():
x = open(input('Enter File Name (Example - test.txt): '))
global lst []
lst = [createList (x)]
print(perkSort(lst))
main ()