日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python 笔试面试及常用技巧 (1)

發布時間:2023/11/28 生活经验 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 笔试面试及常用技巧 (1) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 交換兩個數字

In [66]: x, y = 1, 2In [67]: x
Out[67]: 1In [68]: y
Out[68]: 2

賦值的右側形成了一個新的元組,左側立即解析(unpack)那個(未被引用的)元組到變量 x 和 y。

2. 鏈式比較

In [71]: y = 5In [72]: 1 < y < 10
Out[72]: TrueIn [73]: 10 < y < 20
Out[73]: False

3. 使用三元操作符進行條件賦值

三元操作符是 if-else 語句也就是條件操作符的一個快捷方式:

[表達式為真的返回值] if [表達式] else [表達式為假的返回值]
x = 1 if x < 10 else 0

在列表推導式中使用三元運算符

In [70]: [x**2 if x > 5 else x**3 for x in range(10)]
Out[70]: [0, 1, 8, 27, 64, 125, 36, 49, 64, 81]

4. 多行字符串

  • 使用反斜杠

  • 使用三引號

  • 使用括號(將長字符串包含在括號中)

5. 解包操作

In [74]: aa = [1, 2, 3]In [75]: x, y, z = aaIn [76]: x, y, z
Out[76]: (1, 2, 3)

6. 打印引入模塊的文件路徑

如果你想知道引用到代碼中模塊的絕對路徑,可以使用下面的技巧:

import threading
import socketprint(threading)
print(socket)#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

7. 字典、集合、列表推導

In [77]: [i for i in range(10)]
Out[77]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]In [78]: {i:i*i for i in range(10)}
Out[78]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}In [79]: (i*2 for i in range(10))
Out[79]: <generator object <genexpr> at 0x0000000003BEA3A8>In[57]: dic = {"name": "Tom", "age": 30, "country": "USA"}
In[58]: {k:v for k, v in dic.iteritems()}
Out[58]: {'age': 30, 'country': 'USA', 'name': 'Tom'}
# 翻轉字典的 key value 值
In[59]: {v:k for k, v in dic.iteritems()}
Out[59]: {30: 'age', 'Tom': 'name', 'USA': 'country'}

8. 文件共享

Python 允許運行一個 HTTP 服務器來從根路徑共享文件,下面是開啟服務器的命令:

# Python 2
python -m SimpleHTTPServer# Python 3
python3 -m http.server

上面的命令會在默認端口也就是 8000 開啟一個服務器,你可以將一個自定義的端口號以最后一個參數的方式傳遞到上面的命令中。

9. 查看對象的內置方法

In [81]: dir(aa)
Out[81]: 
['__add__','__class__',
...'append','count','extend','index','insert','pop','remove','reverse','sort']

10. in 語句簡化操作

if x == 1 or x == 2 or x == 3 or x ==4
## 替換為
if x in [1, 2, 3, 4]

11. 連接字符串

  In [82]: cc = ['I', 'love', 'you']In [83]: ' '.join(cc)Out[83]: 'I love you'

12. 翻轉字符串/列表

* 使用 reverse() 翻轉列表本身
* 使用 reversed() 翻轉產生新列表
* 使用切片翻轉
In [82]: cc = ['I', 'love', 'you']In [84]: cc.reverse()In [85]: cc
Out[85]: ['you', 'love', 'I']In [86]: for i in reversed(cc):...:     print i...:     IloveyouIn [87]: cc[::-1]
Out[87]: ['I', 'love', 'you']

13. 同時獲取列表索引和值

In [89]: a = ['a', 'b', 'c']In [90]: for i, v in enumerate(a):...:     print i, v...:     0 a1 b2 c

14. 函數返回多個值

    # function returning multiple values.
def x():return 1, 2, 3, 4# Calling the above function.
a, b, c, d = x()
print(a, b, c, d)
#-> 1 2 3 4

15. 使用 * 運算符來 unpack 函數參數

def test(x, y, z):print(x, y, z)testDict = {'x': 1, 'y': 2, 'z': 3}
testList = [10, 20, 30]test(*testDict)
test(**testDict)
test(*testList)#1-> x y z
#2-> 1 2 3
#3-> 10 20 30

16. 如何打開關閉文件

f = open("test.txt")
try:content = f.read()
finally:f.close()## 更好的方法
with open("test.txt") as f:content = f.read()

17. 使用鎖

# 創建鎖
lock = threading.Lock()
# 使用鎖的老方法
lock.acquire()
try:print 'Critical section 1'print 'Critical section 2'
finally:lock.release()## 更好的方法
with lock:print 'Critical section 1'print 'Critical section 2'

18. 字典的 popitem() 是原子操作,多線程沒必要加鎖

In [2]: d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}In [3]: while d:
...:     key, value = d.popitem()...:     print key, '-->', valuematthew --> blue
rachel --> green
raymond --> red

19. 用key-value對構建字典

In [4]: names = ['raymond', 'rachel', 'matthew']
In [5]: colors = ['red', 'green', 'blue']
In [7]: d = dict(zip(names, colors))
In [8]: d
Out[8]: {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}

20. 遍歷一個序列

colors = ['red', 'green', 'blue', 'yellow']
# 正序
for color in sorted(colors):print colors# 倒序
for color in sorted(colors, reverse=True):print colors

21. 將"hello world"轉換為首字母大寫"Hello World"

In[2]: "hello, world".title()
Out[2]: 'Hello, World'

22. a =“info:China 960 beijing”,用正則切分字符串輸出[‘info’, ‘China’, ‘960’, ‘beijing’]

In[7]: import re
In[8]: a ="info:China 960 beijing"In[9]: re.split(":| ", a)
Out[9]: ['info', 'China', '960', 'beijing']

23. a = “hello world” 去除多余空格只留一個空格

str.split()

注意:當使用空格作為分隔符時,對于中間為空的項會自動忽略

In[20]: " ".join(a.split())
Out[20]: 'hello world'

24. 如何實現 [“1,2,3”] 變為 [‘1’, ‘2’, ‘3’]

In[21]: a = ["1,2,3"]In[22]: a[0].split(",")
Out[22]: ['1', '2', '3']

25. 字典操作中 del 和 pop 有什么區別

del 可以根據 key 來刪除對應的元素,沒有返回值;

pop 可以根據 key 彈出該 key 對應的 value,然后可以接收它的返回值;

In[24]: a = {"a":1, "b":2, "c":3}In[25]: del a["a"]In[26]: a
Out[26]: {'b': 2, 'c': 3}In[27]: re = a.pop("b")
In[28]: re
Out[28]: 2

26. 如何在一個函數內部修改全局變量

num = 5
def func():global numnum = 4
func()
print(num)  # 4

27. 談下 Python 的 GIL?

GIL 是 Python 的全局解釋器鎖,同一進程中假如有多個線程運行,一個線程在運行 Python 程序的時候會占用 Python 解釋器(加了一把鎖即 GIL),使該進程內的其他線程無法運行,等該線程運行完后其他線程才能運行。如果線程運行過程中遇到耗時操作,則解釋器鎖解開,使其他線程運行。所以在多線程中,線程的運行仍是有先后順序的,并不是同時進行。

多進程中因為每個進程都能被系統分配資源,相當于每個進程有了一個 Python 解釋器,所以多進程可以實現多個進程的同時運行,缺點是進程系統資源開銷大。

28. 簡述面向對象中 new 和 init 區別?

  • __new__至少要有一個參數 cls,代表當前類,此參數在實例化時由 Python 解釋器自動識別。

  • __new__必須要有返回值,返回實例化出來的實例,這點在自己實現__new__時要特別注意,可以 return 父類(通過 super(當前類名, cls))__new__出來的實例,或者直接是 object 的__new__出來的實例。

  • __init__有一個參數 self,就是這個__new__返回的實例,__init__在__new__的基礎上可以完成一些其它初始化的動作,__init__不需要返回值。

  • 如果__new__創建的是當前類的實例,會自動調用__init__函數,通過 return 語句里面調用的__new__函數的第一個參數是 cls 來保證是當前類實例,如果是其他類的類名;那么實際創建返回的就是其他類的實例,其實就不會調用當前類的__init__函數,也不會調用其他類的__init__函數。

29. s=“ajldjlajfdljfddd”,去重并從小到大排序輸出"adfjl"?

In[33]: s = "ajldjlajfdljfddd"In[35]: ''.join(sorted(set(s)))
Out[35]: 'adfjl'

30. 用 lambda 函數實現兩個數相乘?

In[36]: ret = lambda x, y: x * yIn[37]: ret(4, 5)
Out[37]: 20

部分內容來自: www.lightxue.com/transforming-code-into-beautiful-idiomatic-python

總結

以上是生活随笔為你收集整理的Python 笔试面试及常用技巧 (1)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。