#列表相关
*如何去掉list中的重复元素
.使用set(集合)
list1=[1,1,2,3,1,1,2,3,4,5,6,1,1]
list_uniq = list(set(list1))
解答:要善于利用集合的概念:
A set object is an unordered collection of distinct objects. Common uses
include membership testing, removing duplicates from a sequence, and computing
mathematical operations such as intersection, union, difference, and symmetric
difference
有时间了,可以阅读以下集合定义的源码
*如何把字符串转成列表
.使用换行符分割
str = "111\n222\n333\n"
list1 = str.splitlines()
.使用特定字符分割
str2 = "aaa#bbb#ccc#"
list2 = str2.split('#')
*对List进行排序,如何得到元素在原来list中的索引值
list a 排序后,得到a在原来列表中的索引位置。
In [1]: a = [3,4,1,7,2]
In [2]: enumerate(a)
Out[2]:
In [3]: list(enumerate(a))
Out[3]: [(0, 3), (1, 4), (2, 1), (3, 7), (4, 2)]
In [4]: from operator import itemgetter
In [5]: sorted(enumerate(a), key=itemgetter(1))
Out[5]: [(2, 1), (4, 2), (0, 3), (1, 4), (3, 7)]
In [6]: [index for index, value in sorted(enumerate(a), key=itemgetter(1))]
Out[6]: [2, 4, 0, 1, 3]
大杀器:
In [7]: import numpy as np
In [8]: np.argsort([3,4,1,7,2])
#字典相关
*如何合并两个字典
d1 = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
d2 = {2: 2, 4: 4, 6: 6, 8: 8, 0: 0}
for k,v in d2.items():d1[k] = d1.setdefault(k,0) + v
*字典中获取某个值,若key不存在返回-1
d={}
d.get('key1', -1)
*设置置字典的值,若key不存在设置默认值[]
d={}
d.setdefault(d, []).append(pagenumber)
setdefault 函数的定义如下:setdefault(key[, default])
若key在字典中,返回key的值,若key不在字典中,返回default的值。默认情况下default设 置为None。
*字典的一个值map到多个value值,如何操作?
比较两个字典,并做相应操作some_dict = { 'zope':'zzz', 'python':'rocks' }another_dict = { 'python':'rocks', 'perl':'$' }
方法1:print "Intersects:", [k for k in some_dict if k in another_dict]
方法2:(在量比较大的时候,该方法优于方法1) 为什么?看源码。print "Intersects:", filter(another_dict.has_key, some_dict.keys())说明:filter函数原型:filter(func, seq)调用一个布尔函数func 来迭代遍历每个seq 中的元素; 返回一个使func 返回值为ture 的元素的序列。
*处理序列中的每一个元素。
rlist = map(fun, alist)
#可以用来处理字符串的每个字符
str = "abcdefghijklmn"
alist = list(str)
rlist = map(fun, alist)
*有两个字典:
dict_A = {12:'rb', 32:'mcs', 31:'time', 433:'ss'}
list_A = ['time', 'ss', 'mcs', 'rb']
我想将dict_A按照list_A的顺序得到如下:
list_B = [31, 433,32,12]
法1:
In [31]: dict_A = {12:'rb', 32:'mcs', 31:'time', 433:'ss'}
In [32]: list_A = ['time', 'ss', 'mcs', 'rb']
In [33]: print [ k for v in list_A for k in dict_A if dict_A[k] == v ]
[31, 433, 32, 12]
法3:
rev_A = dict((v,k) for k, v in dict_A.items())
list_A = ['time', 'ss', 'mcs', 'rb']
list_B = [rev_A[k] for k in list_A]
阅读(2772) | 评论(0) | 转发(3) |