python面試的100題(12)

25.求出列表全部奇數並構造新列表

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

26.用一行python代碼寫出1+2+3+10248

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

描述

reduce() 函數會對參數序列中元素進行累積。

函數將一個數據集合(鏈表,元組等)中的全部數據進行下列操做:用傳給 reduce 中的函數 function(有兩個參數)先對集合中的第 一、2 個元素進行操做,獲得的結果再與第三個數據用 function 函數運算,最後獲得一個結果。

語法

reduce() 函數語法:

reduce(function, iterable[, initializer])

參數

  • function -- 函數,有兩個參數

  • iterable -- 可迭代對象

  • initializer -- 可選,初始參數

返回值

返回函數計算結果。

實例

如下實例展現了 reduce() 的使用方法:

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

27.Python中變量的做用域?(變量查找順序)

函數做用域的LEGB順序google

1.什麼是LEGB?spa

L: local 函數內部做用域code

E: enclosing 函數內部與內嵌函數之間htm

G: global 全局做用域

B: build-in 內置做用

python在函數裏面的查找分爲4種,稱之爲LEGB,也正是按照這是順序來查找的

28.字符串 "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='')

參數

  • 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函數

描述

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() 方法的語法:

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)

 

本文全部名詞及函數解釋均來自「菜鳥教程」。

相關文章
相關標籤/搜索