其他
这 26个 Python 技巧,你肯定还不知道!
(点击上方公众号,可快速关注)
转自:机器之心
易于学习
超高的通用性
具备大量模块和库
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")
# 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("Hello World")
>>> dir(dir)
print(emojize(":thumbs_up:"))
print("Hello World!")
place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)
$ howdoi for loop in java
$ howdoi undo commits in git
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)
def someFunction(a, b):
print(a + b)
return
# these do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)
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)
y = map(lambda x : x + 1 , x)
# prints out [2,3,4]
print(list(y))
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
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)
>>> print(file)
<open file 'file.txt', mode 'r' at 0x10d30aaf0>
def __repr__(self):
return "<some description here>"
someInstance = someClass()
# prints <some description here>
print(someInstance)
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')
return x + 2
Vector = List[float]
Matrix = List[Vector]
def addMatrix(a : Matrix, b : Matrix) -> Matrix:
result = []
for i,row in enumerate(a):
result_row =[]
for j, col in enumerate(row):
result_row += [a[i][j] + b[i][j]]
result += [result_row]
return result
x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)
user_id = uuid.uuid4()
print(user_id)
source my-project/bin/activate
pip install all-the-modules
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
看完本文有收获?请转发分享给更多人
关注「大数据与机器学习文摘」,成为Top 1%
好文章,我在看❤️