List: list.append(x) list.extend(lis) list.insert(i, x) list.remove(x) list.pop(i) #会同时返回移除的值,如果没有设置i,则返回最后一个值 del list[i] del list[i:j] list.index(x) #返回x第一次出现的位置 list.count(x) #返回x出现的次数 list.sort() #sorted() 见blog sort高级用法 list.reverse() #list快速创建: lis = [x**2 for x in range(10)] [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] ----------------------------------- [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] [[row[i] for row in matrix] for i in range(4)] ------------------------------------ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] zip: >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> zipped [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zipped) >>> x == list(x2) and y == list(y2) True
Dictionary: >>> a = dict(one=1, two=2, three=3) >>> b = {‘one‘: 1, ‘two‘: 2, ‘three‘: 3} >>> c = dict(zip([‘one‘, ‘two‘, ‘three‘], [1, 2, 3])) >>> d = dict([(‘two‘, 2), (‘one‘, 1), (‘three‘, 3)]) >>> e = dict({‘three‘: 3, ‘one‘: 1, ‘two‘: 2}) >>> a == b == c == d == e True del d[key] dic.clear() #Remove all items from the dictionary. dic.copy() #Return a shallow copy of the dictionary dic.get(key[, default]) #f default is not given, it defaults to None dic.pop(key[, default]) #If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. dic.popitem() #Remove and return an arbitrary (key, value) pair from the dictionary. dic.items() #Return a copy of the dictionary’s list of (key, value) pairs. dic.keys() #Return a copy of the dictionary’s list of keys dic.values() #eturn a copy of the dictionary’s list of values dic.iteritems() dic.iterkeys() dic.itervalues()
set: python的set和其他语言类似, 是一个无序不重复元素集。 基本功能包括关系测试和消除重复元素. 集合对象还支持union(合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算. sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。 s = set([3,5,9,10]) #创建一个数值集合 t = set("Hello") #创建一个唯一字符的集合 ------------ set([‘H‘, ‘e‘, ‘l‘, ‘o‘]) a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(项在t中,但不在s中) d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 用set去除列表中重复元素 >>> [i for i in set([11,22,33,44,11,22])] [33, 11, 44, 22]
时间: 2024-10-12 01:19:19