python - 冒泡排序算法和“int”对象不可下标
问题描述
我已经有很长一段时间了,但我无法解决下面第 4 行代码中发生的错误('int' object is not subscriptable)。
我希望将我的计数器变量与数组中的前一个索引进行比较,如果前一个索引处的元素较大,则交换它们。
任何建议,将不胜感激!
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))enter code here
解决方案
在行中:
list_of_numbers = temp
list_of_numbers
您正在为导致错误的变量分配一个整数。
因此,请使用:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers[j] = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
或更好的变量交换:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
list_of_numbers[j],list_of_numbers[j-1] = list_of_numbers[j-1],list_of_numbers[j]
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
推荐阅读
- java - JavaFX - 窗格大小属性绑定
- caching - 我如何知道服务人员通过 Workbox 缓存的响应的日期时间?
- angular - 在动态创建的组件中将上下文传递给模板
- sql-server - 在开始交易中开始交易
- php - LemonWay MoneyIn3DInit 响应 262
- c# - 加入主详细信息时Linq查询非常慢
- node.js - 服务器中的 Socket.io 反复断开连接,而在客户端却没有
- python - IPython 与 Jupyter
- apache-kafka - 使用 KafkaConsumer 的 listTopics() 时出现误报 kafka-authorizer.log
- mobile - Detox 自动化库可以自动化混合和 Web 应用程序吗?