a=[1,2,3,4,5,6,7,8,9,10] res=[i for i in a if i%2==1] print(res)
結果爲:[1, 3, 5, 7, 9]html
sum=sum([1,2,3,10248]) print(sum)
結果爲:10254python
方法2express
from functools import reduce num1 = reduce(lambda x,y :x+y,[1,2,3,10248]) print(num1)
reduce函數api
def add(x, y) : # 兩數相加 return x + y t1=reduce(add, [1,2,3,4,5]) # 計算列表和:1+2+3+4+5 print(t1) t2=reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函數
print(t2)
結果爲15,15函數
參考地址:http://www.runoob.com/python/python-func-reduce.htmlui
函數做用域的LEGB順序google
1.什麼是LEGB?spa
L: local 函數內部做用域code
E: enclosing 函數內部與內嵌函數之間htm
G: global 全局做用域
B: build-in 內置做用
python在函數裏面的查找分爲4種,稱之爲LEGB,也正是按照這是順序來查找的
"123"
轉換成 123
,不使用內置api,例如 int()
方法一: 利用 str
函數
def atoi(s): num = 0 for v in s: for j in range(10): if v == str(j): num = num * 10 + j return num
atoi (表示 ascii to integer)是把字符串轉換成整型數的一個函數,
str() 函數
描述
str() 函數將對象轉化爲適於人閱讀的形式。
語法
如下是 str() 方法的語法:
class str(object='')
參數
返回值
返回一個對象的string格式。
如下展現了使用 str() 方法的實例:
s = 'RUNOOB' str(s) 輸出結果:'RUNOOB' dict = {'runoob': 'runoob.com', 'google': 'google.com'}; str(dict) 輸出結果:"{'google': 'google.com', 'runoob': 'runoob.com'}"
方法二: 利用 ord
函數
def atoi(s): num = 0 for v in s: num = num * 10 + ord(v) - ord('0') return num
描述
ord() 函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度爲1的字符串)做爲參數,返回對應的 ASCII 數值,或者 Unicode 數值,若是所給的 Unicode 字符超出了你的 Python 定義範圍,則會引起一個 TypeError 的異常。
語法
如下是 ord() 方法的語法:
ord(c)
參數
c -- 字符。
返回值
返回值是對應的十進制整數。
實例
如下展現了使用 ord() 方法的實例:
ord('a') 結果爲:97
ord('b')
結果爲:98
ord('c')
結果爲:99
方法三: 利用 eval
函數
def atoi(s): num = 0 for v in s: t = "%s * 1" % v n = eval(t) num = num * 10 + n return num
描述
eval() 函數用來執行一個字符串表達式,並返回表達式的值。
語法
如下是 eval() 方法的語法:
eval(expression[, globals[, locals]])
參數
expression -- 表達式。
globals -- 變量做用域,全局命名空間,若是被提供,則必須是一個字典對象。
locals -- 變量做用域,局部命名空間,若是被提供,能夠是任何映射對象。
返回值
返回表達式計算結果。
實例
如下展現了使用 eval() 方法的實例:
x = 7 eval( '3 * x' ) 結果爲:21 eval('pow(2,2)') 結果爲:4 eval('2 + 2') 結果爲:4 n=81 eval("n + 4")
結果爲:85
方法四: 結合方法二,使用 reduce
,一行解決
from functools import reduce def atoi(s): return reduce(lambda num, v: num * 10 + ord(v) - ord('0'), s, 0)