【发布时间】:2015-12-27 13:24:03
【问题描述】:
我有一个 txt 文件,其中包含以下方式的数据:
13
56
9
32
99
74
2
不同文件中的每个值。我创建了三个函数:
第一个是交换值
def swap(lst,x,y):
temp = lst[x]
lst[x] = lst[y]
lst[y] = temp
第二个功能是对值进行排序:
def selection_sort(lst):
for x in range(0,len(lst)-1):
print(lst)
swap(lst,x,findMinFrom(lst[x:])+ x)
第三个功能是从列表中找出最小值:
def findMinFrom(lst):
minIndex = -1
for m in range(0,len(lst)):
if minIndex == -1:
minIndex = m
elif lst[m] < lst[minIndex]:
minIndex = m
return minIndex
现在,我如何从包含数字的文件中读取并打印它们?
提前致谢!
我用过:
def main():
f = []
filename = input("Enter the file name: ")
for line in open(filename):
for eachElement in line:
f += eachElement
print(f)
selectionSort(f)
print(f)
main()
但仍然无法正常工作!有什么帮助吗?
【问题讨论】:
-
请在此处阅读并应用帮助->游览。它声明“没有闲聊”,尽管您的帖子包含“提前致谢”
-
你的交换函数有一个多余的
temp变量,它的主体可以写在一行中;lst[x], lst[y] = lst[y], lst[x],为什么要搞得这么复杂? -
Anthon,我知道这一行,但不推荐,因为它只存在于 python 中,所以这对我作为程序员来说实际上是一种不好的做法。
-
这些错误信息是从哪里来的?在创建 Python 之前,我在 Occam2 中使用了并行赋值。 wikipedia 列出了 10 种可以做到这一点的编程语言,但并不详尽。
标签: python file sorting python-3.x