阅读本文需要大约 2 分钟。
1、三元表达式
if condition:
x = 1
else:
x = 0
print(x)
x = 1 if condition else 0
print(x)
2、使用下划线分隔大数
num2 = 10000000
total = num1 + num2
print(total)
# 110000000
num2 = 10_000_000
total = num1 + num2
print(total)
# 110000000
num2 = 10_000_000
total = num1 + num2
print( f"{total:,}")
# 110,000,000
3、使用上下文管理器with
file_contents = f.read()
f.close()
words = file_contents.split( " ")
word_count = len(words)
print(word_count)
file_contents = f.read()
words = file_contents.split( " ")
word_count = len(words)
print(word_count)
4、使用 enumerate
index = 0
for name in names:
print(index,name)
index += 1
for index,name in enumerate(names):
print(index,name)
5、使用 zip
roles = [ '丹妮莉丝·坦格利安', '琼恩·雪诺', '艾莉亚·史塔克', '提利昂·兰尼斯特']
for index,name in enumerate(names):
print( f"{name} 扮演 {roles [index]}")
roles = [ '丹妮莉丝·坦格利安', '琼恩·雪诺', '艾莉亚·史塔克', '提利昂·兰尼斯特']
for name,role in zip(names,roles):
print( f"{name} 扮演 {role}")
基特·哈灵顿 扮演 琼恩·雪诺
麦茜·威廉姆斯 扮演 艾莉亚·史塔克
彼特·丁拉基 扮演 提利昂·兰尼斯特
>>> b=[ 1, 2, 3, 4, 5]
>>> c=[ 'A', 'B', 'C', 'D']
>>>
>>> list(zip(a,b,c)]
[( 'a', 1, 'A'), ( 'b', 2, 'B'), ( 'c', 3, 'C')]
>>>
6、开箱
>>> print( "a=",a, "b=",b, "c=",c, "d=",d)
a= 1 b= 2 c= [ 3, 4, 5] d= 6
7、输入密码时使用 getpass
请输入密码:mypassword
>>> password
'mypassword'
>>> from getpass import getpass
>>> password2 = getpass( "请输入密码:")
请输入密码:
>>> password2
'123456'
>>>
8、使用 map 函数
... return x ** 2
...
>>> map(square, [ 1, 2, 3, 4, 5]) # 计算列表各个元素的平方
[ 1, 4, 9, 16, 25]
>>> map( lambda x: x ** 2, [ 1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[ 1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map( lambda x, y: x + y, [ 1, 3, 5, 7, 9], [ 2, 4, 6, 8, 10])
[ 3, 7, 11, 15, 19]
8、使用 reduce 函数
... return x + y
...
>>> reduce(add, [ 1, 2, 3, 4, 5]) # 计算列表和:1+2+3+4+5
15
>>> reduce( lambda x, y: x+y, [ 1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
15
reduce() 函数语法:
10、使用 help dir 函数获取帮助
>>> help(smtpd)
Help on module smtpd:
NAME
smtpd - An RFC 5321 smtp proxy with optional RFC 1870 and RFC 6531 extension
s.
DESCRIPTION
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody ', unless this flag is
set. The setuid call will fail if this program is not run as root (
in
which case, use this flag).
--version
-V
Print the version number and exit.
--class classname
-c classname
>>> from datetime import datetime
>>> dir(datetime)
['__add__ ', '__class__ ', '__delattr__ ', '__dir__ ', '__doc__ ', '__eq__ ', '__forma
t__ ', '__ge__ ', '__getattribute__ ', '__gt__ ', '__hash__ ', '__init__ ', '__init_su
bclass__ ', '__le__ ', '__lt__ ', '__ne__ ', '__new__ ', '__radd__ ', '__reduce__ ', '_
_reduce_ex__ ', '__repr__ ', '__rsub__ ', '__setattr__ ', '__sizeof__ ', '__str__ ', '
__sub__ ', '__subclasshook__ ', 'astimezone ', 'combine ', 'ctime ', 'date ', 'day ', '
dst ', 'fold ', 'fromisoformat ', 'fromordinal ', 'fromtimestamp ', 'ho ur', 'isocalen
da r', 'isoformat ', 'isoweekday ', 'max ', 'microsecond ', 'min ', 'minute ', 'month ',
'now ', 'replace ', 'resolution ', 'second ', 'strftime ', 'strptime ', 'time ', 'time
stamp ', 'timetuple ', 'timetz ', 'today ', 'toordinal ', 'tzinfo ', 'tzname ', 'utcfro
mtimestamp ', 'utcnow ', 'utcoffset ', 'utctimetuple ', 'weekday ', 'yea r']
>>>