我有一个非常长的二维列表,其中包含以下形式的字符串
[[Month, Item, Price],[Month, Item, Price],.......]]
我按字母顺序排列的假短版 2d 列表是
msl =[['March', 'cook', '4.53'], ['March', 'book', '3.23'], ['June', 'clothes', '1.52'], ['December', 'clothes', '3.42']]
我想做的是编写没有字典或 lambda 的代码,以按项目的字母顺序对项目进行排序。例如,而不是[['March','cook','4.53'],['March','book','3.23']
它,[['March','book','3.23'],['March','cook','4.53']...]]
但我写的代码似乎不起作用,我不知道为什么。我写了以下
if msl[h][0] == msl[h+1][0] : # If month is the same as next month
print "true"
size = len( msl ) # start an item dictionary sort(msl[i][1])
unsorted = True
while unsorted :
unsorted = False
i = 0
while i < size-1 :
if msl[i][1] > d[i+1][1] : #if the item is greater than the next
print "true again"
temp = d[i] # temp = current sublist
d[i] = d[i+1] # current sublist becomes next sublist
d[i+1] = temp # next sublist becomes current sublist
unsorted = True
i = i + 1
else :
h= h+1
我在那里写“真”来检查程序的进程在哪里,它对所有这些都打印出来,但是当我尝试打印出新的 msl 时,什么都没有出现。是否可以编写类似while month remains the same, sort items
使用 .sort 方法将其应用于项目索引但重新排列整个子列表的内容?