【问题标题】:Match each sublist item with every item in every other sublist (python)将每个子列表项与每个其他子列表中的每个项匹配(python)
【发布时间】:2017-08-19 13:45:44
【问题描述】:

我有一个板列表列表,boardsboards 包含许多子列表,每个子列表中都有相同类型的板。本质上:[[...], [...], ...]

假设第一个子列表是 1,第二个子列表是 2。我需要将 1 的每个元素与 2 的每个元素进行比较。所以,我需要 (1[0], 2[0]), (1[0], 2[1])...(1[0], 2[len(2)-1]);(1[0], 2[0])... 对。

问题是,我不知道boards 中有多少子列表,这意味着我不能只做 n 个for 循环。这就是我现在拥有的:

for sublist in boards:
    for board in sublist:
        for board_indices in itertools.permutations(range(len(sublist)), len(boards)):
            matched_boards = [boards[a][j] for a, j in enumerate(i)]

但我想我想多了。我确信有一种更简单、更简单、更易读的方法来做到这一点,但我不确定它是什么。

【问题讨论】:

  • 你的问题有点不清楚。是否要从boards 中的每一对子列表中生成每一对项目?
  • 另外,您发布的代码有点奇怪。您的for board_indices 循环对board_indices 中生成的排列没有任何作用,并且您有一个未定义的变量i
  • @PM2Ring 是的,没错。另外,对i 变量感到抱歉,我试图让我的代码更具可读性,却忘记用board_indices 替换i

标签: python python-3.x loops multidimensional-array itertools


【解决方案1】:

如果您只需要对,您可以将 itertools.combinationsitertools.product 结合起来,以提供每个可能的跨子列表对:

for sublist_pair in itertools.combinations(nested_iter, 2):
    for item_pair in itertools.product(*sublist_pair):
        print(item_pair)

给予:

(1, 'a')
(1, 'b')
(1, 'c')
(2, 'a')
(2, 'b')
(2, 'c')
(3, 'a')
(3, 'b')
(3, 'c')
(1, 0.1)
(1, 0.2)
(1, 0.3)
(2, 0.1)
(2, 0.2)
(2, 0.3)
(3, 0.1)
(3, 0.2)
(3, 0.3)
('a', 0.1)
('a', 0.2)
('a', 0.3)
('b', 0.1)
('b', 0.2)
('b', 0.3)
('c', 0.1)
('c', 0.2)
('c', 0.3)

【讨论】:

  • 怀疑您的第二个解决方案是 OP 想要的,但我想我们只能拭目以待。 :)
猜你喜欢
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2014-04-05
  • 2014-09-22
相关资源
最近更新 更多