如何并行查找嵌套列表中的元素

发布于 2025-01-26 04:20:44 字数 361 浏览 2 评论 0原文

我有一个elements的列表a = ['a','b','c','d']和嵌套列表b = [{'55','a a' },{'4','t'},{'x','y','zx'},{'b','d'},{'66','c'}]> 。
此外,每个元素只能出现在b的一个子列表中。

我想从a中找到每个元素,从包含它的b的子列表的索引([0,3,3,4,3])。假设来自a的所有元素出现在b中的某个地方。

对于我的数据大小,使用嵌套循环并不实用。

I have a list of elements A = ['a', 'b', 'c', 'd'] and a nested list B = [{'55','a'}, {'4','t'}, {'x','y','zx'}, {'b','d'}, {'66','c'}].
In addition, each element can appear only in one sub-list of B.

I want to find, for each element from A, the index of the sub-list from B that contains it ([0, 3, 4, 3]). Assume that all the elements from A appear somewhere in B.

Using a nested loop isn't practical for the size of my data.

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

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

发布评论

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

评论(1

偏爱自由 2025-02-02 04:20:44

首先为每个项目中的B中构建字典,然后在A上使用列表理解:

d = {k:i for i,s in enumerate(B) for k in s}
# {'55': 0, 'a': 0, 't': 1, '4': 1,
#  'zx': 2, 'y': 2, 'x': 2, 'd': 3,
#  'b': 3, 'c': 4, '66': 4}

out = [d[x] for x in A]

或者,如果您不确定A的所有元素都在B中:

out = [d.get(x, -1) for x in A]

输出:输出:

[0, 3, 4, 3]

使用:使用:

A = ['a', 'b', 'c', 'd']
B = [{'55','a'}, {'4','t'}, {'x','y','zx'}, {'b','d'}, {'66','c'}]

First build a dictionary of the positions in B for each item, then use a list comprehension on A:

d = {k:i for i,s in enumerate(B) for k in s}
# {'55': 0, 'a': 0, 't': 1, '4': 1,
#  'zx': 2, 'y': 2, 'x': 2, 'd': 3,
#  'b': 3, 'c': 4, '66': 4}

out = [d[x] for x in A]

Or, if you are not sure that all elements of A are in B:

out = [d.get(x, -1) for x in A]

Output:

[0, 3, 4, 3]

Used input:

A = ['a', 'b', 'c', 'd']
B = [{'55','a'}, {'4','t'}, {'x','y','zx'}, {'b','d'}, {'66','c'}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文