项目:将列表li1 = [1, 6, 4, 3, 7, 9]倒序输出为[9, 7, 6, 4, 3, 1]
li2 = ['a', 'm', 's', 'g']倒序输出为['g', 's', 'm', 'a']
1.根据python内置的方法'sort':
li1 = [1, 6, 4, 3, 7, 9]
li2 = ['a', 'm', 's', 'g']
li1.sort(reverse=True)
li2.sort(reverse=True)
print(li1, li2)
2.直接使用reverse:
li1 = [1, 6, 4, 3, 7, 9]
li2 = ['a', 'm', 's', 'g']
li1.reverse()
li2.reverse()
print(li1, li2)
3.利用list切片:
li1 = [1, 6, 4, 3, 7, 9]
li2 = ['a', 'm', 's', 'g']
print(li1[::-1])
print(li2[::-1])
4.利用算法进行转换,这里需要用到深层copy:
import copy
li2 = ['a', 'm', 's', 'g']
li3 = copy.deepcopy(li2)
count = len(li2)
for i in li2:
if count > 0:
li2[int(li3.index(i))] = li3[count - 1]
count -= 1
print(li2)