This chapter describespython編寫【list列表反轉】的5種方法
"""
Summarize algorithm questions that have been asked before
一、List inversion problem,五種方法:
1、reverse
2、reversed(list)
3、切片
4、sort()
5、sorted(list)
"""
import sys
a_list = [1, 2, 3, 4, 'abc', 'ee']
def reverse_sort1():
"""
一、list排序反轉:
方法1、使用reverse()方法反轉
:return:
"""
print("原來的list:", a_list)
list.reverse()
print("轉換後的list:", a_list)
def reverse_sort2():
"""
一、list排序反轉:
方法2、使用內置函數reversed(list)
注意:This gets an iterator,而非一個list,所以需要list進行轉換一下
:return:
"""
after_list = reversed(a_list)
print("List inversion results(迭代對象):", after_list)
print("The result of list inversion is converted into a list:", list(a_list))
def reverse_sort3():
"""
一、list排序反轉:
方法3、使用【切片】
list [ start: end : step]
- start 表示起始位置,Included when omittedend之前的所有元素
- end 表示終止位置(不包括end),Included when omittedstart的所有元素
- step 步長,默認為1,Positive numbers are indexed from left to right,Negative numbers are from right to left
:return:
"""
after_list = a_list[::-1]
print("Slice convertedlist:", after_list)
def reverse_sort4():
"""
一、list排序反轉:
方法4、使用【sort()方法】
注意:只能排序listAll are of the same type
:return:
"""
a_list = [1, 2, 3, 6, 8, 9, 12]
# a_list = [1, 2, 3, 6, 8, 9, 12, 'aaa']
# a_list = ['aaa', 'aa', 'a']
a_list.sort(reverse=True)
print("sort轉換後的list:", a_list)
def reverse_sort5():
"""
一、list排序反轉:
方法5、使用【sorted()方法】
注意:只能排序listAll are of the same type
:return:
"""
a_list = [1, 2, 3, 6, 8, 9, 12]
# a_list = [1, 2, 3, 6, 8, 9, 12, 'aaa']
after_list = sorted(a_list, reverse=True)
print("sort轉換後的list:", after_list)
if __name__ == '__main__':
reverse_sort1()
# reverse_sort2()
# reverse_sort3()
# reverse_sort4()
# reverse_sort5()