【发布时间】:2018-07-09 21:09:20
【问题描述】:
这个问题基本上是让我写一个二维数组来存储乐队名称和他们的销售额。 然后它要求我编写一个程序,根据销售数量使用冒泡排序对列表进行排序。 前两个部分相当简单并且工作正常。但是,它后来要求我允许它让用户输入乐队的名称并使用线性搜索获得他们的图表位置。这是我正在努力解决的部分。
myList = [[53,"band1"],[26,"band2"],[923,"band3"],[31,"band4"],[44,"band5"],
[55,"band6"],[231,"band7"]]
def bubbleSort(myList):
for passnum in range(len(myList)-1,0,-1):
for i in range(passnum):
if myList [i]>myList[i+1]:
top7 = myList[i]
myList[i] = myList[i+1]
myList[i+1] = top7
x = int(input("Enter a band name: "))
found = False
for i in range(len(myList)):
if(myList[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break
if(found == False):
print("%d is not in list"%x)
bubbleSort(myList)
print(myList)
这是输出: 输入乐队名称:band4 回溯(最近一次通话最后): 文件“python”,第 10 行,在 ValueError: int() 以 10 为底的无效文字:'band4'
【问题讨论】:
-
您的代码有:
x = int(input("Enter a band name: "))。当您尝试将字符串转换为 int 时,这是预期的行为。 -
如何解决?
-
不要将其转换为
int。只需对字符串进行搜索即可。
标签: python