How to ask for an input and bubble sort that input?
本问题已经有最佳答案,请猛点这里访问。
这是我第一次用Python编写代码,我创建了一个对给定列表进行气泡排序的代码。这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 | def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = ["hi",50,93,"/",77,31,"",55,20] bubbleSort(alist) print(alist) |
我试图向用户请求列表,而不是将列表存储在代码中,但我不知道如何在Python中这样做。有人能帮我一下吗?
一种可能的方法是将参数读取为命令行参数。像这样的:
1 2 3 4 5 6 7 8 9 | import sys def main(): # Some Code for arg in sys.argv[1:]: print(arg) if __name__ == '__main__': main() |
另一种方法是在运行时使用"原始输入()"读取输入:
1 2 | s = raw_input() numbers = map(int, s.split()) |
看看python的内置方法和函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = raw_input('Enter the list to sort (seperated by spaces): ').rstrip() alist = alist.split(' ') bubbleSort(alist) print(alist) |