从最小到最大对列表元组进行排序(仅使用循环和条件而不使用内置排序)

sort a list-tuples from smallest to largest (using only loops and conditions without built-in sort )

我按照以下方式从小到大排列了一个数字列表:

my_list = [-5,3,0,9,-8,1]
for i in range(len(my_list)):
  for x in range(len(my_list)-1):
    if my_list[x] > my_list[x+1]:
      my_list[x], my_list[x+1] = my_list[x+1], my_list[x] 
print(my_list)

输出是:[-8, -5, 0, 1, 3, 9]

现在我有了一个元组列表:

list_tuple = [(1, 5), (1, 2), (1, 4), (1, 3), (1, 1)]

我想按元素[1]从小到大同样排列 变成这样:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)]

不使用内置排序

list_tuple = [(1, 5), (1, 2), (1, 4), (1, 3), (1, 1)]

n = len(list_tuple)

for i in range (0, n):
    for x in range (0, n-i-1):
        if list_tuple[x][1] > list_tuple[x+1][1]:
            y = list_tuple[x]
            list_tuple[x] = list_tuple[x+1]
            list_tuple[x+1] = y

print (list_tuple)

输出:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)]