1.如何迴圈獲得下標,使用 enumerate
ints = ['a','b','c','d','e','f'] for idx, val in enumerate(ints): print idx, val
結果:
0 a
1 b
2 c
3 d
4 e
5 f
------------------------------------------------------------------------------------------
2.python 中的switch 替代語法,使用字典
xdef test(par): print par def test1(): print 1000 def test3(par): print par def f(x): return { 'a': test, 'b': test1, }.get(x, test3) print f('a')(100) print f(4)(100)
結果:
100
100
------------------------------------------------------------------------------------------
3.如何在非建立全域性變數的時候使用全域性變數,使用global關鍵字
globvar = 0 def test4(): global globvar globvar = 10 def test5(): print globvar test4() test5()
結果為10
------------------------------------------------------------------------------------------
4.為什麼是string.join(list)而不是list.join(string)
my_list = ["Hello", "world"]
print "-".join(my_list)
#為什麼不是 my_list.join("-") 。。。。這個....
因為所有可迭代物件都可以被連線,而不只是列表,但是連線者總是字串
------------------------------------------------------------------------------------------
5.如何反向輸出一個字串?
'test'[::-1]
------------------------------------------------------------------------------------------
6.如何隨機生成大寫字母和數字組成的字串?
import string, random
''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
------------------------------------------------------------------------------------------
7.如何將一個字串轉成字典?
使用內建模組 ast.literal_eval
import ast
print ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
結果為:{'muffin': 'lolz', 'foo': 'kitty'}
------------------------------------------------------------------------------------------
8.如何填充字串
n = '4'
print n.zfill(3)
n = 4
print '%03d' % n
print "{0:03d}".format(4) # python >= 2.6
結果:
004
004
004
------------------------------------------------------------------------------------------
9.如何判斷一個列表為空?
if not a:
print "List is empty"
#不要用len(a)來判斷
------------------------------------------------------------------------------------------
10.列表append 和extend 的區別?
>>> x = [1, 2]
>>> x.append(3)
>>> x
[1, 2, 3]
>>> x.append([4,5])
>>> x
[1, 2, 3, [4, 5]]
>>>
>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> x
[1, 2, 3, 4, 5]
------------------------------------------------------------------------------------------
11.如何隨機的從列表中獲得變數?
foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
print choice(foo)
------------------------------------------------------------------------------------------
12.如何將列表切成長度相同的序列?
def chunks(l, n): return [l[i:i+n] for i in range(0, len(l), n)]
------------------------------------------------------------------------------------------
13. 列表如何去重?
def f7(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)]
print f7([1,2,3,4,3,2,4,5,6,5,4,3])
結果:[1, 2, 3, 4, 5, 6]
------------------------------------------------------------------------------------------
14.遍歷list的時候刪除某些元素?
#在原有物件上進行修改
somelist[:] = [x for x in somelist if determine(x)]
------------------------------------------------------------------------------------------
15.如何扁平一個二維陣列?
l = [[1,2,3],[4,5,6], [7], [8,9]]
變為[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
1.[item for sublist in l for item in sublist]
2.import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain(*list2d))
print merged
# python >= 2.6
import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))
print merged
3.print sum(list2d,[])
------------------------------------------------------------------------------------------
16.如何獲得list元素的下標?
["foo","bar","baz"].index('bar')
1
------------------------------------------------------------------------------------------
17.如何將一個字典換成object
def dict2obj(args): '把字典遞迴轉化為類' class obj(object): def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, obj(b) if isinstance(b, dict) else b) return obj(args) d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} x = dict2obj(d) print x.a
1
------------------------------------------------------------------------------------------
18.如何合併2字典?
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
我想要最終合併結果在z中,不是x,我要怎麼做?
回答
這種情況下,可以使用
z = dict(x.items() + y.items())
------------------------------------------------------------------------------------------
19.如何對映2列表成一個字典?
兩個列表
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
如何得到
dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
使用zip
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
{'a': 1, 'b': 2, 'c': 3}
------------------------------------------------------------------------------------------
20.排序一個列表所有dict,根據dict的值
lists = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10},{'name':'Art', 'age':40}]
from operator import itemgetter
newlist = sorted(lists, key=itemgetter('name'))
print newlist
結果為:[{'age': 40, 'name': 'Art'}, {'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
------------------------------------------------------------------------------------------