>>> chars = [ c for c in'python']
>>>chars['
p', '
y', '
t', '
h', '
o', '
n']
>>> dict1 =>>> double_dict1 =
>>>double_dict1
>>> set1 =>>> double_set =
>>>double_set
>>> x =>>> y =
>>> z =
>>>z
>>> nums = [1,2,3]>>>nums[::]
[1, 2, 3]
>>> copy_nums =nums[::]
>>>copy_nums
[1, 2, 3]
>>> reverse_nums = nums[::-1]>>>reverse_nums
[3, 2, 1]
>>> a,b = 1, 2>>> a ,b =b,a
>>>a
2>>>b
1
>>> a, *b = 1,2,3>>>a
1>>>b
[2, 3]
或者>>> a, *b, c = 1,2,3,4,5
>>>a
1>>>b
[2, 3, 4]
>>>c
5
>>> deff():
...
return 1, 2, 3, 4...
>>> a, b, c, d =f()
>>>a
1>>>d
4
>>> "".join(["
i", "
love
", "
python"])
'i love python
'
>>> if a > 2 and a < 5:...
pass
...>>> if 2:
...
pass
#沒有使用 field from
defdup(n):
for i in
range(n):
yield
i
yieldi#
使用yield from
defdup(n):
for i in
range(n):
yield
from
[i, i]
for i in dup(3):
(i)>>>001
122
>>> if x == 1 or x == 2 or x == 3:...
pass
...>>> if x in (1,2,3):
...
pass
deffun(x):
if x == 'a'
:
return 1
elif x == 'b'
:
return 2
else
:
return
none
deffun(x):
return .get(x)
>>> for i, e in enumerate(["a","
b","c"
]):...
(i, e)
...0 a
1b2 c
注意區分列表推導式,生成器效率更高>>> g = (i**2 for i in range(5))
>>>g
at 0x10881e518>
>>> for i in
g:...
(i)...01
4916
>>> d =dict()>>> d['
nums']
keyerror:
'nums
'>>>
>>> from collections import
defaultdict
>>> d =defaultdict(list)
>>> d["
nums"]
>>> lang = 'python
'>>> f'
is most popular language in the world''
python is most popular language in the world
'
>>> nums = [1,2,3,3]>>> max(set(nums), key=nums.count)
3或者from collections import
counter
>>>counter(nums).most_common()[0][0]
3
>>> with open("test.txt
", "w"
) as f:
... f.writelines(
"hello
")
>>>isinstance(a, (int, str))true
類似的還有字串的 startswith,endswith
前者對人友好,可讀性更強,後者對計算機友好,支援 obj == eval(repr(obj))
defmakebold(f):
return
lambda: "
" + f() + "
"
defmakeitalic(f):
return
lambda: "
" + f() + "
"@makebold
@makeitalic
defsay():
return
"hello
">>>say()
hello不使用裝飾器,可讀性非常差
defsay():
return
"hello
">>>makebold(makeitalic(say))()
hello
python中高階函式
一等公民 高階函式 高階函式 high order function def counter base def inc step 1 nonlocal base base step return base return inc 上面的counter是高階函式,因為return inc,即返回函式 內...
Python中高階容器
python 中常見的容器為 list set dict tuple 這裡主要探索下不常見的容器 author jiangnan he list set dict tuple import queue 佇列 import heapq 優先佇列 實現堆排序 大小堆 from collections i...
Python的學習 Python中高階函式的應用
變數可以指向函式,函式的引數能接收變數,那麼乙個函式就可以接收另乙個函式作為引數,這種函式就稱之為高階函式。map 函式接收兩個引數,乙個是函式,乙個是序列 map將傳入的函式依次作用到序列的每個元素,並把結果作為新的序列返回 序列 1,2,3,4 的每個元素求絕對值 print list map ...