gpt4 book ai didi

python - 将列表 A 的每个元素与列表 B 的每个元素压缩 - 最佳方法 "pythonie"

转载 作者:行者123 更新时间:2023-11-30 23:09:32 24 4
gpt4 key购买 nike

我有两个要压缩的列表

列表A:

["hello ", "world "]

列表B:

["one", "two", "three"]

我想像这样压缩列表中的元素:

[("hello","one")
("hello","two")
("hello","three")
("world","one")
("world","two")
("world","three")]

显然,我可以使用双 for 循环并附加元素,但我想知道什么是一个好的 pythonie 方法?

最佳答案

这似乎是 itertools.product 的完美用例

>>> import itertools
>>> list(itertools.product(['hello', 'world'], ['one', 'two', 'three']))
[('hello', 'one'), ('hello', 'two'), ('hello', 'three'), ('world', 'one'), ('world', 'two'), ('world', 'three')]

关于python - 将列表 A 的每个元素与列表 B 的每个元素压缩 - 最佳方法 "pythonie",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31144919/

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