欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

10個(gè)易被忽視但應(yīng)掌握的Python基本用法

 更新時(shí)間:2015年04月01日 09:39:09   作者:David Taylor  
這篇文章主要介紹了10個(gè)易被忽視但應(yīng)掌握的Python基本用法,如字典推導(dǎo)、內(nèi)省工具等,主要針對(duì)Python3版本,需要的朋友可以參考下
我一輩子都在寫代碼,但從來(lái)沒(méi)有掌握編碼的精髓。大部分情況下使用Visual Basic,因?yàn)槲矣肰B最舒服。同時(shí)還略微了解一點(diǎn)其他語(yǔ)言(R、C、JavaScript、Applescript、Hypertext和1979年學(xué)習(xí)的BASIC)。幾年前,我決定只用Python,以此來(lái)提高我的編碼能力。在此過(guò)程中重復(fù)發(fā)明了許多輪子,但我并不介意,因?yàn)槲蚁硎芙鉀Q問(wèn)題的樂(lè)趣。同時(shí)有時(shí)能發(fā)現(xiàn)更有效、Python式的解決方案。時(shí)間長(zhǎng)了以后,會(huì)有頓悟的時(shí)刻,意識(shí)到根本沒(méi)必要用困難且冗長(zhǎng)的方式處理問(wèn)題。下面列出10條Python用法,如果我早點(diǎn)發(fā)現(xiàn),也許能節(jié)省很多時(shí)間。

這里沒(méi)有列表推導(dǎo)和lambda函數(shù)。雖然這兩個(gè)用法都是Python式的,效率高也非??幔捎诮?jīng)常在StackOverflow或其他地方碰到,所以學(xué)Python的應(yīng)該都知道這兩個(gè)東西。同時(shí)也沒(méi)有三元運(yùn)算符、裝飾器和生成器,因?yàn)槲液苌儆玫健?/p>

本文還有一個(gè)IPython notebook nbviewer版本。
1. 在Python 2中使用Python 3式的輸出

Python 2與Python 3不兼容,這讓我不知道該選擇哪個(gè)版本的Python。最終我選擇了Python 2,因?yàn)楫?dāng)時(shí)許多我需要用的庫(kù)都與Python 3不兼容。

但實(shí)際上,日常使用中最大的版本差異是輸出(print)和除法行為?,F(xiàn)在我在Python 2的代碼中都用import from future來(lái)導(dǎo)入Python 3的輸出和除法?,F(xiàn)在我用到的幾乎所有庫(kù)都支持Python 3,因此會(huì)很快遷移到Python 3中。
 

mynumber = 5
 
print "Python 2:"
print "The number is %d" % (mynumber)
print mynumber / 2,
print mynumber // 2
 
from __future__ import print_function
from __future__ import division
 
print('nPython 3:')
print("The number is {}".format(mynumber))
print(mynumber / 2, end=' ')
print(mynumber // 2)
 
Python 2:
The number is 5
2 2
 
Python 3:
The number is 5
2.5 2

對(duì)了,對(duì)于C系的那些更喜歡括號(hào)而不是縮進(jìn)的開(kāi)發(fā)者,這里還有一個(gè)彩蛋:
 

from __future__ import braces
File "", line 1
from __future__ import braces
SyntaxError: not a chance

2. enumerate(list)

很明顯,迭代列表時(shí),應(yīng)該同時(shí)迭代其中的元素及其索引,但在很長(zhǎng)一段時(shí)間內(nèi),我都尷尬的使用計(jì)數(shù)變量或切片。
 

mylist = ["It's", 'only', 'a', 'model']
 
for index, item in enumerate(mylist):
  print(index, item)
 
0 It's
1 only
2 a
3 model

3. 鏈?zhǔn)奖容^操作符

由于我以前使用的是靜態(tài)語(yǔ)言(在這些語(yǔ)言中該用法有二義性),從來(lái)沒(méi)有將兩個(gè)比較操作符放在一個(gè)表達(dá)式中。在許多語(yǔ)言中,4 > 3 > 2會(huì)返回False,因?yàn)? > 3的結(jié)果是布爾值,而True > 2將得出False。
 

mynumber = 3
 
if 4 > mynumber > 2:
  print("Chained comparison operators work! n" * 3)
 
Chained comparison operators work!
Chained comparison operators work!
Chained comparison operators work!

4. collections.Counter

Python的集合庫(kù)看上去是最好的。在計(jì)算需要集合中元素的個(gè)數(shù)時(shí),StackOverflow找到的答案是創(chuàng)建有序字典,但我堅(jiān)持使用一個(gè)代碼片段來(lái)創(chuàng)建字典,計(jì)算結(jié)果中元素出現(xiàn)的頻率。直到有一天,我發(fā)現(xiàn)可以用collections.deque。
 

from collections import Counter
from random import randrange
import pprint
 
mycounter = Counter()
 
for i in range(100):
  random_number = randrange(10)
  mycounter[random_number] += 1
 
for i in range(10):
  print(i, mycounter[i])
 
0 10
1 10
2 13
3 6
4 6
5 11
6 10
7 14
8 12
9 8

5. 字典推導(dǎo)

Python開(kāi)發(fā)者的一個(gè)重要標(biāo)志就是理解列表推導(dǎo),但最終我發(fā)現(xiàn)字典推導(dǎo)也很有用,特別是在交換字典的鍵和值的時(shí)候。
 

my_phrase = ["No", "one", "expects", "the", "Spanish", "Inquisition"]
my_dict = {key: value for value, key in enumerate(my_phrase)}
print(my_dict)
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict)
{'Inquisition': 5, 'No': 0, 'expects': 2, 'one': 1, 'Spanish': 4, 'the': 3}
{0: 'No', 1: 'one', 2: 'expects', 3: 'the', 4: 'Spanish', 5: 'Inquisition'}

6. 用subprocess執(zhí)行shell命令

以前,我使用os庫(kù)調(diào)用外部命令處理文件,而現(xiàn)在我可以在Python中以編碼的方式執(zhí)行諸如ffmpeg這樣的復(fù)雜命令進(jìn)行視頻編輯。

(是的,我和我的客戶都使用Windows,如果你們因此鄙視我,我會(huì)大方地接受?。?/p>

注意,用os庫(kù)完成這個(gè)特定命令比用subprocess更好。我只想有一個(gè)大家都熟悉的命令。同時(shí),一般來(lái)說(shuō),在subprocess中使用shell=True參數(shù)是非常糟糕的主意,在這里使用這個(gè)參數(shù)僅僅是為了能在一個(gè)IPython notebook單元中放置命令的輸出。不要自己使用這個(gè)參數(shù)!
 

import subprocess
output = subprocess.check_output('dir', shell=True)
print(output)
Volume in drive C is OS
Volume Serial Number is [REDACTED]
Directory of C:UsersDavidDocuments[REDACTED]
 
2014-11-26 06:04 AM  <DIR>     .
2014-11-26 06:04 AM  <DIR>     ..
2014-11-23 11:47 AM  <DIR>     .git
2014-11-26 06:06 AM  <DIR>     .ipynb_checkpoints
2014-11-23 08:59 AM  <DIR>     CCCma
2014-09-03 06:58 AM      19,450 colorbrewdict.py
2014-09-03 06:58 AM      92,175 imagecompare.ipynb
2014-11-23 08:41 AM  <DIR>     Japan_Earthquakes
2014-09-03 06:58 AM       1,100 LICENSE
2014-09-03 06:58 AM       5,263 monty_monte.ipynb
2014-09-03 06:58 AM      31,082 pocket_tumblr_reddit_api.ipynb
2014-11-26 06:04 AM       3,211 README.md
2014-11-26 06:14 AM      19,898 top_10_python_idioms.ipynb
2014-09-03 06:58 AM       5,813 tree_convert_mega_to_gexf.ipynb
2014-09-03 06:58 AM       5,453 tree_convert_mega_to_json.ipynb
2014-09-03 06:58 AM       1,211 tree_convert_newick_to_json.py
2014-09-03 06:58 AM      55,970 weather_ML.ipynb
       11 File(s)    240,626 bytes
        6 Dir(s) 180,880,490,496 bytes free

7. 字典的.get()和.iteritems()方法

字典的get()方法可以設(shè)置默認(rèn)值,當(dāng)用get()查找的鍵不存在時(shí),返回方法中的默認(rèn)值參數(shù)是很有用的。與列表中的enumerate()相同,可以用鍵值元組迭代字典中的元素。
 

my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'}
 
print(my_dict.get('airspeed velocity of an unladen swallow', 'African or European?n'))
 
for key, value in my_dict.iteritems():
  print(key, value, sep=": ")
 
African or European?
 
quest: Holy Grail
name: Lancelot
favourite_color: blue

8. 用于交換元素的元組解包

在VB中,每當(dāng)需要交換兩個(gè)變量時(shí),都要用要一個(gè)愚蠢的臨時(shí)變量:c = a; a = b; b = c
 

a = 'Spam'
b = 'Eggs'
 
print(a, b)
 
a, b = b, a
 
print(a, b)
 
Spam Eggs
Eggs Spam

9. 內(nèi)省工具Introspection tools

我知道dir()方法,我本以為help()方法和IPython中的?魔法命令是一樣的,但help()的功能更強(qiáng)大。
 

my_dict = {'That': 'an ex-parrot!'}
 
help(my_dict)
Help on dict object:
 
class dict(object)
 | dict() -> new empty dictionary
 | dict(mapping) -> new dictionary initialized from a mapping object's
 | (key, value) pairs
 | dict(iterable) -> new dictionary initialized as if via:
 | d = {}
 | for k, v in iterable:
 | d[k] = v
 | dict(**kwargs) -> new dictionary initialized with the name=value pairs
 | in the keyword argument list. For example: dict(one=1, two=2)
 |
 | Methods defined here:
 |
 | __cmp__(...)
 | x.__cmp__(y) <==> cmp(x,y)
 |
 | __contains__(...)
 | D.__contains__(k) -> True if D has a key k, else False
 |
 | __delitem__(...)
 | x.__delitem__(y) <==> del x[y]
 |
 | __eq__(...)
 | x.__eq__(y) <==> x==y
 |
 
[TRUNCATED FOR SPACE]
 
 |
 | update(...)
 | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
 | If E present and has a .keys() method, does: for k in E: D[k] = E[k]
 | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
 | In either case, this is followed by: for k in F: D[k] = F[k]
 |
 | values(...)
 | D.values() -> list of D's values
 |
 | viewitems(...)
 | D.viewitems() -> a set-like object providing a view on D's items
 |
 | viewkeys(...)
 | D.viewkeys() -> a set-like object providing a view on D's keys
 |
 | viewvalues(...)
 | D.viewvalues() -> an object providing a view on D's values
 |
 | ----------------------------------------------------------------------
 | Data and other attributes defined here:
 |
 | __hash__ = None
 |
 | __new__ =
 | T.__new__(S, ...) -> a new object with type S, a subtype of T

10. PEP-8兼容的字符串連接

PEP8是Python編碼樣式指南。撇開(kāi)其他的不看,PEP8要求每行不能超過(guò)80個(gè)字符,超過(guò)的部分要換行并縮進(jìn)。

可以通過(guò)反斜杠、帶逗號(hào)“,”的圓括號(hào)“()”、或者額外的加號(hào)“+”來(lái)完成換行。但對(duì)于多行字符串,這些解決方案都不夠優(yōu)雅。Python有個(gè)多行字符串記號(hào),即三個(gè)引號(hào),但這樣無(wú)法換行后保持縮進(jìn)。

還有一個(gè)方法,那就是不帶逗號(hào)的圓括號(hào)。我不知道為什么這種方式能工作,但能用就行。
 

my_long_text = ("We are no longer the knights who say Ni! "
        "We are now the knights who say ekki-ekki-"
        "ekki-p'tang-zoom-boing-z'nourrwringmm!")
print(my_long_text)
we are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!

 

相關(guān)文章

  • python?中raise用法

    python?中raise用法

    這篇文章主要介紹了python?中raise用法,Python?允許我們?cè)诔绦蛑惺謩?dòng)設(shè)置異常,就是使用raise?語(yǔ)句來(lái)實(shí)現(xiàn),下面我們就來(lái)看看raise的具體用法,文章內(nèi)容介紹詳細(xì),具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2021-12-12
  • 使用Python寫一個(gè)創(chuàng)意五子棋游戲源代碼

    使用Python寫一個(gè)創(chuàng)意五子棋游戲源代碼

    這篇文章主要給大家介紹了關(guān)于使用Python寫一個(gè)創(chuàng)意五子棋游戲的相關(guān)資料,Python作為一種簡(jiǎn)單易上手的編程語(yǔ)言,能夠輕松實(shí)現(xiàn)五子棋游戲,需要的朋友可以參考下
    2023-08-08
  • python函數(shù)調(diào)用,循環(huán),列表復(fù)制實(shí)例

    python函數(shù)調(diào)用,循環(huán),列表復(fù)制實(shí)例

    這篇文章主要介紹了python函數(shù)調(diào)用,循環(huán),列表復(fù)制實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05
  • python如何使用雙線性插值計(jì)算網(wǎng)格內(nèi)數(shù)據(jù)

    python如何使用雙線性插值計(jì)算網(wǎng)格內(nèi)數(shù)據(jù)

    這篇文章主要介紹了python如何使用雙線性插值計(jì)算網(wǎng)格內(nèi)數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • QT5 Designer 打不開(kāi)的問(wèn)題及解決方法

    QT5 Designer 打不開(kāi)的問(wèn)題及解決方法

    這篇文章主要介紹了QT5 Designer 打不開(kāi)的問(wèn)題及解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Python?jpg快速轉(zhuǎn)png并調(diào)整大小方式

    Python?jpg快速轉(zhuǎn)png并調(diào)整大小方式

    這篇文章主要介紹了Python實(shí)現(xiàn)jpg快速轉(zhuǎn)png并調(diào)整大小方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • TensorFlow低版本代碼自動(dòng)升級(jí)為1.0版本

    TensorFlow低版本代碼自動(dòng)升級(jí)為1.0版本

    這篇文章主要介紹了TensorFlow低版本代碼自動(dòng)升級(jí)為1.0版本,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 使用Python實(shí)現(xiàn)微信提醒備忘錄功能

    使用Python實(shí)現(xiàn)微信提醒備忘錄功能

    最近工作比較繁雜,經(jīng)常忘事,有時(shí)候記了備忘錄結(jié)果卻忘記看備忘錄,但是微信是每天都會(huì)看的,于是就想到寫 一個(gè)基于微信的提醒系統(tǒng)。這篇文章主要介紹了使用Python實(shí)現(xiàn)微信提醒備忘錄功能,需要的朋友可以參考下
    2018-12-12
  • python 腳本生成隨機(jī) 字母 + 數(shù)字密碼功能

    python 腳本生成隨機(jī) 字母 + 數(shù)字密碼功能

    本文通過(guò)一小段簡(jiǎn)單的代碼給大家分享基于python 腳本生成隨機(jī) 字母 + 數(shù)字密碼功能,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-05-05
  • Python實(shí)現(xiàn)二叉樹(shù)前序、中序、后序及層次遍歷示例代碼

    Python實(shí)現(xiàn)二叉樹(shù)前序、中序、后序及層次遍歷示例代碼

    這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn)二叉樹(shù)前序、中序、后序及層次遍歷的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05

最新評(píng)論