Python 列表 使用技巧

1.列表表達式與列表排序

列表中的元素也是可迭代的對象如列表、元組等時,要根據這些元素的某個子元素對列表排序,常規排序方式失效,需要用sorted()函數並指定key。
題目:

輸入一組數到列表nums,請找到列表中任意兩個元素相加能夠等於9的元素,形成一個元組,使其小數在前大數在後,如:(2,7),(1,8)。重複的元組元素只保留一個,結果按元組第一個元素從小到大順序輸出。
【樣例輸入】

numbers:3,4,5,7,2,8,1

【樣例輸出】

[(1, 8), (2, 7), (4, 5)]

示例解答如下:

def get_tuple(num_list):
    temp_list = []
    for i in num_list:
        if (9 - i) in num_list:
            min = (9 - i) if (i >= (9 - i)) else i
            max = i if min == (9 - i) else (9 - i)
            if (min,max) not in temp_list:
                temp_list.append((min,max))
    return temp_list

nums = input()
num_list = [int(i) for i in nums.split(',')]

result_list = get_tuple(num_list)
result_list = sorted(result_list,key=lambda i:i[0])

print(result_list)

代碼運行演示如下:
list comprehension
說明:
[int(i) for i in nums.split(',')]是列表表達式,有更高的執行效率;
sorted(result_list,key=lambda i:i[0])對列表進行排序,因爲列表中有多個元素,要根據每個元素的第一個子元素來排序,必須使用key來指定排序所依據的元素,同時還是用了lambda表達式,給定一個元素,返回第一個子元素。

2.按照子列表中的某個元素對列表進行排序

例如,有一個列表unsorted_list = [['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']],需要按照每個子列表中的第4個元素(即整數)對列表進行排序,有3種方式:
方式一——使用lambda表達式

unsorted_list = [['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']]
sorted_list = sorted(unsorted_list, key=lambda x: x[3])
print(unsorted_list)
print(sorted_list)

打印:

[['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']]
[['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm'], ['a', 'b', 'c', 5, 'd']]

顯然,得到了排序後的新列表;
其中,lambda表達式返回每個子列表的第4個元素,sorted函數使用lambda表達式的返回值作爲key來對列表排序。

方式二——使用itemgetter類

from operator import itemgetter
unsorted_list = [['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']]
sorted_list = sorted(unsorted_list, key=itemgetter(3), reverse=True)
print(unsorted_list)
print(sorted_list)

打印:

[['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']]
[['a', 'b', 'c', 5, 'd'], ['i', 'j', 'k', 4, 'm'], ['e', 'f', 'g', 3, 'h']]

顯然,得到了排序的結果;
可以用reverse參數使結果倒序。

方式三——調用列表的sort()方法

unsorted_list = [['a', 'b', 'c', 5, 'd'], ['e', 'f', 'g', 3, 'h'], ['i', 'j', 'k', 4, 'm']]
print(unsorted_list)
unsorted_list.sort(key=lambda x: x[3])
print(unsorted_list)

顯然,得到了正確的排序結果;
調用sort()方法是對原列表排序,不會產生新的列表。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章