Python_列表操作2

1.使用sort()方法对列表进行永久性排序:

colorsList=['hong','cheng','huang','lv']

colorsList.sort() #正序排序
print(colorsList)

colorsList.sort(reverse=True) #倒序 关键字:reverse=True
print(colorsList)

执行结果:

['cheng', 'hong', 'huang', 'lv']
['lv', 'huang', 'hong', 'cheng']

2.使用函数sorted()对列表进行临时排序:(sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。)

print('原列表:')
print(colorsList)

print('调用sorted()方法升序后的临时列表:')
print(sorted(colorsList)) #升序

print('调用sorted()方法后的原列表:')
print(colorsList)


print('原列表:')
print(colorsList)

print('调用sorted()方法倒序后的临时列表:')
print(sorted(colorsList,reverse=True)) #倒序

print('调用sorted()方法后的原列表:')
print(colorsList)

执行结果:

原列表:
['hong', 'cheng', 'huang', 'lv']
调用sorted()方法升序后的临时列表:
['cheng', 'hong', 'huang', 'lv']
调用sorted()方法后的原列表:
['hong', 'cheng', 'huang', 'lv']
原列表:
['hong', 'cheng', 'huang', 'lv']
调用sorted()方法倒序后的临时列表:
['lv', 'huang', 'hong', 'cheng']
调用sorted()方法后的原列表:
['hong', 'cheng', 'huang', 'lv']

3.reverse()方法:反转列表元素的排列顺序

colorsList=['hong','cheng','huang','lv']

print('原列表:')
print(colorsList)

colorsList.reverse()
print('调用reverse()方法第一次反转后的列表:')
print(colorsList) #第一次反转

colorsList.reverse()
print('调用reverse()方法第二次反转后的列表:')
print(colorsList) #第二次反转

执行结果:

原列表:
['hong', 'cheng', 'huang', 'lv']
调用reverse()方法第一次反转后的列表:
['lv', 'huang', 'cheng', 'hong']
调用reverse()方法第二次反转后的列表:
['hong', 'cheng', 'huang', 'lv']

原文地址:https://www.cnblogs.com/myfy/p/11465684.html