分数是浮云,小结一下吧

ImN1 2013-06-23 12:44:23
备注:下面的方法只有少量是自己写的,大部分均为参考别人所得,由于只是平常笔记,没有一一记下原文出处了

Python中对列表list求交集

方法1
遍历b1,如果某个元素同时也存在于b2中,则返回
b1=[1,2,3]
b2=[2,3,4]
b3 = [val for val in b1 if val in b2]
print b3
运行结果如下
[2, 3]

方法2
把列表转换为集合,利用集合操作符求出交集,然后再转换回列表类型
b1=[1,2,3]
b2=[2,3,4]
b3=list(set(b1) & set(b2))
print b3
运行结果如下
[2, 3]
# 交为 & ,并为 | ,差为 -,不能使用 or

前面的例子中两个list都是简单的单元素列表,还有一种比较特殊的情况,就是有嵌套类型的
b1=[1,2,3]
b2=[[2,4],[3,5]]
b3 = [filter(lambda x: x in b1,sublist) for sublist in b2]
print b3
运行结果如下
[[2], [3]]

下面是文档中对filter的解释

filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.


交换矩阵数组的行列
>>> a=[[1,2,3],[4,5,6]]
>>> list(zip(*a))
[(1, 4), (2, 5), (3, 6)]


求二维嵌套序列交集(部分单元相交)
a = [[8, 6, 3], [3, 4, 5], [5, 2, 7]]
b = [[2, 5, 4], [6, 8, 5]]
c = ((x, y) for x, y, z in b)
print([i for i in a if (i[1], i[0]) in c])

[[8, 6, 3], [5, 2, 7]]

字典求并集(覆盖,不覆盖则为x, y交换位置)
>>> x={'a':1, 'b':2}
>>> y={'a':4, 'c':3}
>>> dict(x, **y)
{'a': 4, 'b': 2, 'c': 3}

字典依据键名求交集
>>>dict((k,v) for k,v in x.items() if k in y)
{'a': 1}

字典依据键名求差集
>>>dict((k,v) for k,v in x.items() if k not in y)
{'b': 2}


字典行列交换
>>> a={'c': [11, 22, 33, 44], 'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]}
>>> [dict(zip(a, x)) for x in zip(*[a[y] for y in a])]
[{'a': 1, 'b': 5, 'c': 11}, {'a': 2, 'b': 6, 'c': 22}, {'a': 3, 'b': 7, 'c': 33}, {'a': 4, 'b': 8, 'c': 44}]

>>> k=tuple(a.keys())
>>> [dict(zip(k, x)) for x in zip(*[a[y] for y in k])]
[{'a': 1, 'b': 5, 'c': 11}, {'a': 2, 'b': 6, 'c': 22}, {'a': 3, 'b': 7, 'c': 33}, {'a': 4, 'b': 8, 'c': 44}]

In [167]: a={'a':[1,2,3,4], 'b':[5,6,7,8]}
In [168]: b = [{k: a[k][i] for k in a} for i in range(len(list(a.values())[0]))]
In [169]: b
Out[169]: [{'a': 1, 'b': 5}, {'a': 2, 'b': 6}, {'a': 3, 'b': 7}, {'a': 4, 'b': 8}]

...全文
201 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ImN1 2013-06-28
  • 打赏
  • 举报
回复
送分也没人要啊……真冷清
ImN1 2013-06-24
  • 打赏
  • 举报
回复
引用 3 楼 zhouchongzxc 的回复:
什么是矩阵的交并差?
矩阵指的是每个单元个数都相同的二维数组 就是指二维数组的交并差,分整个单元相同和部分相同两种情况 整个单元相同可以视为一维看待,所以重点是部分相同的情况 [[1,2],[3,4]] & [[5,6],[3,4]] = [[3,4]] 部分相交看顶楼例子
ImN1 2013-06-23
  • 打赏
  • 举报
回复
不知道numpy对矩阵交并差有没有更方便的处理,懂的人不妨跟贴分享一下
ChongQingJin28 2013-06-23
  • 打赏
  • 举报
回复
什么是矩阵的交并差?
bugs2k 2013-06-23
  • 打赏
  • 举报
回复

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧