http://blog.csdn.net/pipisorry/article/details/39234557
Python中的“真值”
在Python和Django模板系統中,以下這些對象相當於布爾值的False
-
空列表([] )
-
空元組(() )
-
空字典({} )
-
空字符串('' )
-
零值(0 )
-
特殊對象None
-
對象False(很明顯)
1. 你也可以在自定義的對象裏定義他們的布爾值屬性(python的高級用法)。
2. 除以上幾點以外的所有東西都視爲`` True``
python列表操作
python列表的插入、拋出操作
list的插入操作是調用函數listinsert來實現的。該函數的流程如下:
1、解析參數。
2、調用靜態函數ins1進行插入操作。
list的插入操作對索引值的處理在函數ins1中進行,相關處理過程如下:
1、將列表的條目數賦值給n;
2、如果索引值小於0,則將索引值增加n;如果仍小於0,則將索引值賦值爲0;
3、如果索引值大於n,則將索引值賦值爲n。
拋出操作當條目索引爲負數時的處理
list的拋出操作是將指定索引位置的條目從列表中刪除並且返回該條目的值。list的拋出操作是調用函數listpop來實現的。
對索引值index的相關處理過程如下:
1、如果index小於0,則將index增加列表本身的條目數;
2、如果index仍小於0或大於列表條目數,則輸出錯誤信息提示索引值超出範圍。
源碼中將操作位置初始化爲-1,所以如果沒有指定拋出位置,則默認拋出最後一個條目。
List slices with step (a[start:end:step])帶步長列表切片
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2]
[0, 2, 4, 6, 8, 10]
List slice assignment列表切片賦值
>>> a = [1, 2, 3, 4, 5]
>>> a[2:3] = [0, 0]
>>> a
[1, 2, 0, 0, 4, 5]
>>> a[1:1] = [8, 9]
>>> a
[1, 8, 9, 2, 0, 0, 4, 5]
>>> a[1:-1] = []
>>> a
[1, 5]
Zipping and unzipping lists and iterables
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]
1. s.clear()
2. del s[:]
3. s[:] = []
4. s *= 0
Flattening lists
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
>>> sum(a, [])
[1, 2, 3, 4, 5, 6]
>>> [x for l in a for x in l]
[1, 2, 3, 4, 5, 6]
>>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> [x for l1 in a for l2 in l1 for x in l2]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8]
Note: according to Python's
documentation on sum,itertools.chain.from_iterable is the preferred method for this.
python中怎麼對一個列表賦值並修改不影響原來的列表?
-
簡單列表的拷貝
已知一個列表,求生成一個新的列表,列表元素是原列表的複製
a=[1,2]
b=a這種其實並未真正生成一個新的列表,b指向的仍然是a所指向的對象。
後果:如果對a或b的元素進行修改,a,b的值同時發生變化:a.remove(1)則對應b也變爲[2]
-
可以使用以下方法解決
a=[1,2]
b=a[:]這樣修改a對b沒有影響。修改b對a沒有影響。
-
複雜列表的拷貝
可以使用copy模塊中的deepcopy函數。修改測試如下:
import copya=[1,[2]]
b=copy.deepcopy(a)
列表初始化值設置
music_tag = dict() for music_name in music_names: music_tag.setdefault(music_name, []) for filename in filenames: if music_name in [line.strip() for line in open(join(DIR, filename))]: music_tag[music_name] += filename.split('.')[0]python的for循環從兩個不同列表中同時取出兩個元素
zip(): 如果你多個等長的序列,然後想要每次循環時從各個序列分別取出一個元素,可以利用zip()方便地實現:
ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
for (a,b,c) in zip(ta,tb,tc):
print(a,b,c)
每次循環時,從各個序列分別從左到右取出一個元素,合併成一個tuple,然後tuple的元素賦予給a,b,c
zip()函數的功能,就是從多個列表中,依次各取出一個元素。每次取出的(來自不同列表的)元素合成一個元組,合併成的元組放入zip()返回的列表中。zip()函數起到了聚合列表的功能。
將python列表中每個元素用,分開寫入文件中(最後一個元素後面不加,)
a = ['12', '34', '45'] s = ','.join(a) print(s) 12,34,45
python文件中的科學計數法的數字讀入列表中並排序
for line in word_dist_file: word_dist_list = line.strip().split() word_dist_list = sorted([float(word_dist) for word_dist in word_dist_list], reverse=True)
python列表查找某個元素
1. (推薦,不用搜索列表兩次,更快)
try: k = l.index(4) #index查找不存在的元素會出異常 except: k = 32.
if 4 not in l: k = 3 else: k = l.index(4)
一個for循環中每次迭代輸出兩個列表對應的元素及對應的索引號
users = [1,2,3] items = [4,5,6] for index, (user, item) in enumerate(zip(users, items)): print(index, user, item) 0 1 4 1 2 5 2 3 6
Largest and smallest elements (heapq.nlargest andheapq.nsmallest)
>>> a = [random.randint(0, 100) for __ in range(100)]
>>> heapq.nsmallest(5, a)
[3, 3, 5, 6, 8]
>>> heapq.nlargest(5, a)
[100, 100, 99, 98, 98]
兩個list相與操作
list1 = [1,2] list2 = [2,3] print(list1 and list2) [2, 3]python中求兩個list的交集,兩個list是否有交集
list1 = [1,2] list2 = [2,3] print(set(list1).intersection(set(list2))) {2}
python字典操作
python dict字典的key必須是hashable的
key不能是list, set(否則出錯TypeError: unhashable type: 'list'), 但可以是tuple
python dict字典for循環輸出
dict1 = {1: 1, 2: 1, 3: 1} for i in dict1: #等價於dic1.keys() print(i) 1 2 3python 字典中如何通過value 找出key
任何時刻dict.keys()和dict.values()的順序都是對應的:
try:
return dict.keys()[dict.values().index(value)] #python3中要修改爲list(dict.keys())[list(dict.values()).index(value)]
except ValueError:
pass
Note:往dict中添加元素,keys和values加入後都是無序的!但是加入之後相對位置不變。
python字典設置value初始類型,指定字典的value類型
1. collections.defaultdict([default_factory[,...]])
default_factory指定字典的value類型from collections
import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Note:defaultdict()參數設置成int,那麼就設置字典值的初始值爲0了
2.dict.setdefault(key, default=None) 和get()類似, 但如果鍵不存在於字典中,將會添加鍵並將值設爲default
上面代碼效率高於下面的等效代碼:
>>> d = {}
>>> for k, v in s:
... d.setdefault(k, []).append(v)
如果給default_dict傳入int,則可以用來計數:
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
指定類型的變化
d = defaultdict(int) d[3] += 2.284684 print(d) defaultdict(<class 'int'>, {3: 2.284684})
Using default dictionaries to represent simple trees
>>> import json
>>> tree = lambda: collections.defaultdict(tree)
>>> root = tree()
>>> root['menu']['id'] = 'file'
>>> root['menu']['value'] = 'File'
>>> root['menu']['menuitems']['new']['value'] = 'New'
>>> root['menu']['menuitems']['new']['onclick'] = 'new();'
>>> root['menu']['menuitems']['open']['value'] = 'Open'
>>> root['menu']['menuitems']['open']['onclick'] = 'open();'
>>> root['menu']['menuitems']['close']['value'] = 'Close'
>>> root['menu']['menuitems']['close']['onclick'] = 'close();'
>>> print json.dumps(root, sort_keys=True, indent=4, separators=(',', ': '))
{
"menu": {
"id": "file",
"menuitems": {
"close": {
"onclick": "close();",
"value": "Close"
},
"new": {
"onclick": "new();",
"value": "New"
},
"open": {
"onclick": "open();",
"value": "Open"
}
},
"value": "File"
}
}
(See https://gist.github.com/hrldcpr/2012250 for more on this.)
Mapping objects to unique counting numbers (collections.defaultdict)
>>> import itertools, collections
>>> value_to_numeric_map = collections.defaultdict(itertools.count().next)
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
>>> value_to_numeric_map['c']
2
>>> value_to_numeric_map['a']
0
print(ui_dict) try: print(ui_dict[(1,3)]) except: try: print(ui_dict[(3,1)]) except: print(0) {(1, 2): '5', (3, 2): '5', (3, 1): '1', (1, 1): '1', (2, 1): '4'} 1
兩個字典合併操作
dict1 = {1:1, 2:1, 3:1} dict2 = {3:2, 4:2, 5:2} dict1.update(dict2) print(dict1)
x = {'a':1, 'b': 2}
python字典排序
對字典按鍵/按值排序,用元組列表的形式返回,同時使用lambda函數來進行;
sorted(iterable[, cmp[, key[, reverse]]]
cmp和key一般使用lambda
對字典按鍵key排序,用元組列表的形式返回
d = {3:5, 6:3, 2:4} ds = sorted(d.items(), key=lambda item:item[0], reverse=True) #d[0]表示字典的鍵 print(ds) [(6, 3), (3, 5), (2, 4)]
對字典按值value排序,用元組列表的形式返回
ds = sorted(d.items(), key=lambda item:item[1], reverse=True) print(ds) [(3, 5), (2, 4), (6, 3)]
print(dict(ds)) #又變成無序的了{2: 4, 3: 5, 6: 3}
分解代碼:d.items() 得到[(鍵,值)]的列表。然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第一個元素d[1]的值來排序。reverse = True表示是需要翻轉的,默認是從小到大,翻轉的話,那就是從大到小。
Ordered dictionaries (collections.OrderedDict)有序字典
>>> m = dict((str(x), x) for x in range(10))
>>> print ', '.join(m.keys())
1, 0, 3, 2, 5, 4, 7, 6, 9, 8
>>> m = collections.OrderedDict((str(x), x) for x in range(10))
>>> print ', '.join(m.keys())
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>>> m = collections.OrderedDict((str(x), x) for x in range(10, 0, -1))
>>> print ', '.join(m.keys())
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
>>> m = {x: 'A' + str(x) for x in range(10)}
>>> m
{0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5: 'A5', 6: 'A6', 7: 'A7', 8: 'A8', 9: 'A9'}
Inverting a dictionary using a dictionary comprehension翻轉字典中的key和value
>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> m
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
>>> {v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Python集合操作
集合類型初始化及加入新元素(已存在就不加入)
s = {2,3,3} print(s) s.add(2) print(s)
Multisets and multiset operations (collections.Counter)
>>> A = collections.Counter([1, 2, 2])
>>> B = collections.Counter([2, 2, 3])
>>> A
Counter({2: 2, 1: 1})
>>> B
Counter({2: 2, 3: 1})
>>> A | B
Counter({2: 2, 1: 1, 3: 1})
>>> A & B
Counter({2: 2})
>>> A + B
Counter({2: 4, 1: 1, 3: 1})
>>> A - B
Counter({1: 1})
>>> B - A
Counter({3: 1})
python元組操作
Named tuples (collections.namedtuple)元素命名的元組
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(x=1.0, y=2.0)
>>> p
Point(x=1.0, y=2.0)
>>> p.x
1.0
>>> p.y
2.0
列表,元組和字符串之間的互相轉換
python中有三個內建函數:str(),tuple()和list()
列表,元組和字符串,他們之間的互相轉換
>>> s = "xxxxx" >>> list(s) ['x', 'x', 'x', 'x', 'x'] >>> tuple(s) ('x', 'x', 'x', 'x', 'x') >>> tuple(list(s)) ('x', 'x', 'x', 'x', 'x') >>> list(tuple(s)) ['x', 'x', 'x', 'x', 'x'] |
>>> "".join(tuple(s)) 'xxxxx' >>> "".join(list(s)) 'xxxxx' >>> str(tuple(s)) "('x', 'x', 'x', 'x', 'x')" |
元組列表轉字典
列表或元組直接轉字典1. rankDict = dict(rank)
即可將元組轉爲字典型
2. dict.fromkeys(S)
S是一個列表或元組...
將S中的元素作爲字典的key,value默認爲None,也可以指定一個初始值,代碼示例:
- myDict = dict.fromkeys('hello', True)
- for k in myDict.keys():
- print(k, myDict[k])
- h True
- e True
- l True
- o True
30 Python Language Features and Tricks You May Not Know About
Hidden features of Python [closed]
Python: Tips, Tricks and Idioms