一行代碼寫python


1、一行代碼更新python數組中對象屬性滿足某一值的元素

arr = [{'a': 3,'c':4}, {'d':5,'a': 4}, {'a': 1,'b':2}]
[x.update(x,a=9) for x in arr if x.get('a') == 4]
print arr
輸出:

[{'a': 3, 'c': 4}, {'a': 9, 'd': 5}, {'a': 1, 'b': 2}]

2、求10000以內的質數

from math import sqrt    
N = 10000
[ p for p in   range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]

輸出(以N=100爲例):

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

3、元素爲對象的數組排序

arr = [{'a': 3,'c':4}, {'d':5,'a': 4}, {'a': 1,'b':2}]
arr2=sorted(arr,key=lambda e:e.get('a'),reverse=False)

輸出:

[{'a': 1, 'b': 2}, {'a': 3, 'c': 4}, {'a': 4, 'd': 5}]





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