[英]List sorting with bubble sort (list of list)
我必须将文本文件放到列表中,以便最终看起来像这样:
[["Afghanistan",647500.0,25500100],["Albania",28748.0,2821977],...,["Zimbabwe",390580.0,12973808]]
因此,由函数readcountries()定义的列表列表,我想根据列表列表中的一个参数(即填充为国家名称后的第二个数字)。
这就是我到目前为止
def bubblesort():
Countries = readcountries()
for i in range(0,len(Countries)):
madeSwap = False
for j in range (0,len(Countries)-(i+1)):
if Countries[j][2] > Countries[j+1][2]:
temp = Countries[j+1]
Countries[j+1][2] = Countries[j][2]
Countries[j] = temp
madeSwap = True
if not madeSwap:
return
但是由于某种原因,我对此无法进行任何排序,甚至在以后也看不到排序列表。 欢迎任何帮助
问题在这里, Countries[j+1][2] = Countries[j][2]
您必须替换为Countries[j+1] = Countries[j]
也
你必须调用这个
if not madeSwap:
return
在外面
并返回清单
def bubblesort():
Countries = [["Afghanistan",647500.0,3],["Albania",28748.0,1],["Zimbabwe",390580.0,2]]
for i in range(0,len(Countries)):
madeSwap = False
for j in range (0,len(Countries)-(i+1)):
if Countries[j][2] > Countries[j+1][2]:
temp = Countries[j+1]
Countries[j+1] = Countries[j]
Countries[j] = temp
madeSwap = True
if not madeSwap:
return Countries
return Countries
>>> bubblesort()
[['Afghanistan', 647500.0, 1], ['Zimbabwe', 390580.0, 2], ['Albania', 28748.0, 3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.