Python:创建一个长度为两个列表的交集的矩阵,其元素是数字集

2024-09-30 08:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.5,我想知道是否有更有效的方法来实现这一点。你知道吗

  • 我有两个列表(list1list2)。你知道吗
  • 每个列表中的每个元素都是数字的set。你知道吗
  • 在下面的示例中,list1基本上是1x4“矩阵”,而list2是1x3“矩阵”。你知道吗
  • 我想做一个4x3矩阵,给出list1中每个元素与list2中每个元素的交集的长度

下面是一些可以工作的示例代码,但是当我的列表长度为数千时,它会有点慢。你知道吗

有没有更快/更好的方法??你知道吗

谢谢你!你知道吗

list1 = [{1,2,3}, {4,5,6}, {1,2,9}, {4,5,10}] # 1 x 4 "matrix"
list2 = [{1,3,9}, {4,2,8}, {1,0,10}] # 1 x 3 "matrix"

myoutputmatrix = []

for aset in list1:
    small_list = [len(aset & asecondset) for asecondset in list2]
    myoutputmatrix .append(small_list)

myoutputmatrix # [[2, 1, 1], [0, 1, 0], [2, 1, 1], [0, 1, 1]]

Tags: 方法in元素示例列表for矩阵matrix

热门问题