我是Python的新手,我试图向用户询问所需的一些元素,然后要求在单独的行中输入每个元素,然后对该输入进行气泡排序。
import readline
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 = readlines('Enter the list to sort \n', 'r').rstrip()
alist = alist.split(',')
bubbleSort(alist)
print alist.readlines()
如果我将readlines
更改为raw_input
,则代码正常工作,但输入只进行一行。有人可以帮助我如何指定元素'数字以及如何在新行中获得每个输入?
答案 0 :(得分:2)
试试这个:
bubbleSort([raw_input('Enter element') for _ in range(input('Enter the number of elements needed'))])
一个班轮应该做的伎俩
EXPLAIN :::
基本上,一旦你撤消列表推导和pythonic格式,我们在这里做的就是三件事。
#Asking for the number of elements needed and making a loop that will repeat that many times
for _ in range(input('Enter the number of elements needed')):
#in each loop, retrieve an element from the user and put it into a list for later
listvariable.append(raw_input('enter element'))
#Then at the end we're taking that list and putting it through the bubbleSort
bubbleSort(listvariable)
使用上面一行解决方案中的列表推导简化了代码。
答案 1 :(得分:1)
我相信这是您正在寻找的基础知识。
ntimes = raw_input("Enter the number of lines")
ntimes = int(ntimes)
alist = []
while (ntimes > 0):
ntimes -= 1
alist.append(raw_input('Enter the list to sort \n').split(','))
print alist
答案 2 :(得分:0)
Python 3:
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
return alist
def main():
lines = []
print("Enter names (hit enter twice to bubble-sort):")
while True:
line = input("%3i: " % (len(lines)+1))
if not line:
break
lines.append(line)
print("Sorted names:")
for i, name in enumerate(bubbleSort(lines), 1):
print("%3i. %s" % (i, name))
main()
输入和输出:
Enter names (hit enter twice to bubble-sort):
1: Mark
2: Jim
3: Kayne
4: Foobar
5: Zulu
6: Anna
7: Yeti
8:
Sorted names:
1. Anna
2. Foobar
3. Jim
4. Kayne
5. Mark
6. Yeti
7. Zulu