Skip to main content
 首页 » 编程设计

python之将每个子列表项与每个其他子列表中的每个项目匹配(python)

2024年10月01日8傻小

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

假设第一个子列表是 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)] 

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

请您参考如下方法:

如果它只是你想要的对,你可以结合 itertools.combinations 和 itertools.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)