## A到Z個python小技巧

Python是世界上最流行的編程語言之一,這有如下原因:
* python很容易學習
* python有豐富的使用場景
* python有大量的模塊和庫作為支持
在日常工作中,我使用python完成數據科學的工作,在工作中,我總結了一些有用的技巧。
我嘗試把這些技巧在字母a-z進行了分類。下面是具體的小技巧
## all or?any
python之所以如此流行的原因是,它的可讀性非常高。而且有很多的語法糖,看下面的例子:
~~~
x = [True, True, False]
if any(x):
print("At least one True")
if all(x):
print("Not one False")
if any(x) and not all(x):
print("At least one True and one False")
~~~
## bashplotlib
你想在控制臺繪制圖表?
`pip install bashplotlib`
bashplotlib是在控制臺畫圖表的庫。
## collections
python有很好的默認集合類,有時候我們需要一些增強的python類來完成對數據的處理,看下面列子:
~~~
from collections import OrderedDict, Counter
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
# Counts the frequency of each character
y = Counter("Hello World!")
~~~
## dir
你想知道python對象內部有什么東西嗎?dir方法可以幫助你查看,看代碼:
~~~
dir()
dir("Hello World")
dir(dir)
~~~
這在你使用一個新的包時會非常有用。
## emoji
python的emoji表情表:
`$ pip install emoji`
看代碼:
~~~
from emoji import emojize
print(emojize(":thumbs_up:"))
~~~
??
## from __future__ import
想提前嘗試python的新特性,可以使用 __future__語法。
~~~
from __future__ import print_function
print("Hello World!")
~~~
## geopy
python的地理位置包
`$ pip install geopy`
使用這個包可以完成地址和經緯度的轉換和距離檢測等操作。看代碼:
~~~
from geopy import GoogleV3
place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)
~~~
## howdoi
不知道一些事情該怎么做?用`howdoi `這個命令吧
`$ pip install howdoi`
看使用例子:
~~~
$ howdoi vertical align css
$ howdoi for loop in java
$ howdoi undo commits in git
~~~
## inspect
想知道別人包的代碼是是什么?使用inspect模塊吧。看代碼:
~~~
import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)
~~~
## Jedi
python的代碼補全器,如果沒有用IDE編寫python代碼,可以嘗試一下這個
## **kwargs
python的參數語法糖,看代碼:
~~~
dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
print(a + b)
return
# these do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)
~~~
## List comprehensions
集合操作的語法糖,是不是很繞 哈哈
~~~
numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]
cities = ['London', 'Dublin', 'Oslo']
def visit(city):
print("Welcome to "+city)
for city in cities:
visit(city)
~~~
## map
函數式編程語法糖,不過現在很少用了
~~~
x = [1, 2, 3]
y = map(lambda x : x + 1 , x)
# prints out [2,3,4]
print(list(y))
~~~
## newspaper3k
用python讀新聞,這個太極客了
~~~
$ pip install newspaper3k
~~~
## Operator overloading
操作符重載是python的一個重要特性。在定義一個類時,可以用操作符重載來對兩個對象做簡單判斷。看代碼:
~~~
class Thing:
def __init__(self, value):
self.__value = value
def __gt__(self, other):
return self.__value > other.__value
def __lt__(self, other):
return self.__value < other.__value
something = Thing(100)
nothing = Thing(0)
# True
something > nothing
# False
something < nothing
# Error
something + nothing
~~~
## pprint
`print`方法可以做簡單輸出,如果要輸出復雜對象,可以使用`pprint`
~~~
import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)
~~~
## Queue
python的隊列實現
#### \_\_repr\_\_
`__repr__`方法將一個對象用字符串表示。在定一個一個類時,可以重寫`__repr__`方法
~~~
class someClass:
def __repr__(self):
return "<some description here>"
someInstance = someClass()
# prints <some description here>
print(someInstance)
~~~
## sh
用python執行shell命令
~~~
from sh import *
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')
~~~
## Type hints
python是一個弱類型語言,為了安全,還可以對方法參數聲明類型。
~~~
def addTwo(x : Int) -> Int:
return x + 2
~~~
## uuid
生成uuid
~~~
import uuid
user_id = uuid.uuid4()
print(user_id)
~~~
## Virtual environments
為自己的項目虛擬一個獨立的python環境,防止模塊污染
~~~
python -m venv my-project
source my-project/bin/activate
pip install all-the-modules
~~~
## wikipedia
python訪問維基百科
~~~
import wikipedia
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)
~~~
## xkcd
Humour is a key feature of the Python language?—?after all, it is named after the British comedy sketch show [Monty Python’s Flying Circus](https://en.wikipedia.org/wiki/Monty_Python%27s_Flying_Circus). Much of Python’s official documentation references the show’s most famous sketches.
The sense of humour isn’t restricted to the docs, though. Have a go running the line below:
import antigravity
Never change, Python. Never change.
## YAML
ymal數據的python客戶端
`$ pip install pyyaml`
`import yaml`
PyYAML lets you store Python objects of any datatype, and instances of any user-defined classes also.
## zip
將兩個集合變為一個字典
~~~
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
~~~
python是一個非常靈活的語言。里面還有很多內置的語法糖,一方面方便了我們的編碼,另外一方面也會造成一些困惑。有奇怪的語法記得多谷歌。
**阿達老師-孩子身邊的編程專家**
*完整課程請關注阿達老師,主頁里有完整的課程目錄和觀看地址*
- 空白目錄
- 8.21 做自媒體我學到了什么
- scratch技巧分享系列-調試技巧
- 8.23 論scratch的缺陷
- 9.4 孩子為什么要學編程
- 9.4 好榜樣
- 9.12 python a-z
- 開發網頁很難嗎?
- 9.14 用python識別微表情
- 9.14 todo,給孩子搭建一個自己的網站吧
- 9.16 scratch模擬臺風
- 9.17 python好文分享-列表詳解
- 9.17 臺風怎么形成的,阿達老師做給你
- 9.18 阿達老師科學課-什么是生物
- 9.18 進位加法怎么做?阿達老師用Scratch教給你
- 9.19 樹葉為什么會變黃?和阿達老師一起看下
- 9.19 用Scratch做100以內的減法
- 9.19 小草和山羊的斗智斗勇
- 9.19習大大主持開幕的人工智能大會講了啥
- 9.24 中秋節的月亮為什么那么圓
- 9.27 編程還可以寫歌?你沒看錯
- 10.10
- 10.11 用編程玩物理-什么是引力
- 10.16 jupyter使用
- 10.17 什么是火
- 1024 長度換算
- 你會疊飛機嗎
- 和孩子們一起做繪本-沙漠版小紅帽
- 一分鐘學編程系列-下雪啦
- 一分鐘學編程系列-光合作用
- 一分鐘學編程系列-掛滿禮物的圣誕樹
- 一分鐘學編程系列-太陽系里的星球(一)
- 一分鐘學編程系列-太陽系里的星球(二)
- 為什么學生不喜歡上學(二)-事實性知識的重要性
- 為什么學生不喜歡上學(三)-為什么學生能記住電視里的所有細節, 卻記不住我們告訴他的任何知識?
- 為什么學生不喜歡上學(四)- 抽象概念為什么這么難
- 一分鐘學編程計劃-圣誕節的禮物派對
- 一分鐘學編程系列-火星營救(一)
- 為什么孩子不喜歡上學(五)- 題海戰術有用嗎
- 為什么孩子不喜歡上學(六)- 思考的秘訣是什么