矩阵中行的交集

发布于 2025-01-20 22:56:48 字数 345 浏览 2 评论 0原文

我在Python中有以下列表:

a = [1, 2, 3, 4 ,5]
b = [[1, 2, 3], [2, 3, 4, 5], [3, 4, 5]]

我想与每行b相交a。为此,类似的

d = set(a).intersection(set(b[0]), set(b[1]), set(b[2]))

工作将有效,但我想要迭代方法,因为如果B中的行数增加,那么像这样写所有的行都太多了。另外,如果我在A中占据许多行,则A和B的相应行还需要迭代。我们该怎么办。

我检查了交叉点,但通常它们仅给出2或3或4组的交叉点。交叉点说128套呢?

I have the following lists in python:

a = [1, 2, 3, 4 ,5]
b = [[1, 2, 3], [2, 3, 4, 5], [3, 4, 5]]

I want to intersect a with each row of b. For this something like

d = set(a).intersection(set(b[0]), set(b[1]), set(b[2]))

will work but I want iterative method because if the number of rows in b increases then writing all of them like this is too much. Also if I take many rows in a then intersecting corresponding rows of a and b would also require iteration. What do we do.

I checked intersections but usually they give the intersection of only 2 or 3 or 4 sets. What about intersection say 128 sets.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心病无药医 2025-01-27 22:56:48

你可以在这里做

d = set(a).intersection(*b)

b ,它必须是一个可迭代的,这样它就可以产生与你的系统/实现允许的一样多的项目!来自文档

...union()、intersection()、difference() 的非运算符版本,
symmetry_difference()、issubset() 和 issuperset() 方法将
接受任何可迭代的。

这里的*可迭代解包运算符(文档

将[s] [可迭代]扩展为一系列项目,其中包括
在解包位置的新元组、列表或集合中。

使用问题中定义的 ab ,打印 d 将产生

{3}

预期的输出。

希望这有帮助!如有任何疑问,请告诉我!

You can just do

d = set(a).intersection(*b)

b here just has to be an iterable so it can yield as many items as your system / the implementation allows! From the documentation

...the non-operator versions of union(), intersection(), difference(),
symmetric_difference(), issubset(), and issuperset() methods will
accept any iterable.

The * here is the iterable unpacking operator (documentation) which

expand[s] [the iterable] into a sequence of items, which are included
in the new tuple, list, or set, at the site of the unpacking.

With a and b as defined in your question, printing d would yield output

{3}

just as expected.

Hope this helps! Please let me know if there are any questions!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文