gpt4 book ai didi

Python函数从列表列表中返回二维列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:49 25 4
gpt4 key购买 nike

这里有一个Python问题。我想创建一个函数来从列表列表中返回二维列表。我在itertools中找不到这个函数。

可能的输入 = 如下所示列出 aa 或 ab(不同长度)

aa = [[230, 115, 90, 264], [12, 9, 5], [-1], ['on', 'off']]
ab = [[230, 115, 90, 264], ['on', 'off']]

ab 的输出应该是:

[[230, 'on'],
[230, 'off'],
[115, 'on'],
[115, 'off'],
[90, 'on'],
[90, 'off'],
[264, 'on'],
[264, 'off']]

aa 的输出应该是:

[[230, 12, -1, 'on'],
[230, 12, -1, 'off'],
[230, 9, -1, 'on'],
[230, 9, -1, 'off'],
....
[264, 5, -1, 'off']]

最佳答案

我想你要的是 cartesian product一些可迭代的,例如:

import itertools
import pprint

aa = [[230, 115, 90, 264], [12, 9, 5], [-1], ['on', 'off']]
ab = [[230, 115, 90, 264], ['on', 'off']]

for iterable in [aa, ab]:
pprint.pprint(list(itertools.product(*aa)))

结果:

[(230, 12, -1, 'on'),
(230, 12, -1, 'off'),
(230, 9, -1, 'on'),
(230, 9, -1, 'off'),
(230, 5, -1, 'on'),
(230, 5, -1, 'off'),
(115, 12, -1, 'on'),
(115, 12, -1, 'off'),
(115, 9, -1, 'on'),
(115, 9, -1, 'off'),
(115, 5, -1, 'on'),
(115, 5, -1, 'off'),
(90, 12, -1, 'on'),
(90, 12, -1, 'off'),
(90, 9, -1, 'on'),
(90, 9, -1, 'off'),
(90, 5, -1, 'on'),
(90, 5, -1, 'off'),
(264, 12, -1, 'on'),
(264, 12, -1, 'off'),
(264, 9, -1, 'on'),
(264, 9, -1, 'off'),
(264, 5, -1, 'on'),
(264, 5, -1, 'off')]
[(230, 12, -1, 'on'),
(230, 12, -1, 'off'),
(230, 9, -1, 'on'),
(230, 9, -1, 'off'),
(230, 5, -1, 'on'),
(230, 5, -1, 'off'),
(115, 12, -1, 'on'),
(115, 12, -1, 'off'),
(115, 9, -1, 'on'),
(115, 9, -1, 'off'),
(115, 5, -1, 'on'),
(115, 5, -1, 'off'),
(90, 12, -1, 'on'),
(90, 12, -1, 'off'),
(90, 9, -1, 'on'),
(90, 9, -1, 'off'),
(90, 5, -1, 'on'),
(90, 5, -1, 'off'),
(264, 12, -1, 'on'),
(264, 12, -1, 'off'),
(264, 9, -1, 'on'),
(264, 9, -1, 'off'),
(264, 5, -1, 'on'),
(264, 5, -1, 'off')]

关于Python函数从列表列表中返回二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com