在日常工作中,我经常在摘要下方写下这些内容,
res = []
a = ["A","B","C","D"]
b = [1,2,3,4]
for _a in a:
for _b in b:
res.append((_a,_b))
# or be more simple
#[(_a,_b) for _a in a for _b in b]
[('A', 1),
('A', 2),
('A', 3),
('A', 4),
('B', 1),
('B', 2),
('B', 3),
('B', 4),
('C', 1),
('C', 2),
('C', 3),
('C', 4),
('D', 1),
('D', 2),
('D', 3),
('D', 4)]
我可否知道
>在计算机领域是否有用于此类操作的特殊术语?
>如果有办法,例如一个python模块可以做到这一点?例如我有20个列表,需要列出所有组合吗? itertools可以做到吗?
谢谢
解决方法:
itertools.product正是您需要的:
>>> list(itertools.product("ABCD", "1234"))
[('A', '1'), ('A', '2'), ('A', '3'), ('A', '4'), ('B', '1'),
('B', '2'), ('B', '3'), ('B', '4'), ('C', '1'), ('C', '2'),
('C', '3'), ('C', '4'), ('D', '1'), ('D', '2'), ('D', '3'),
('D', '4')]