gpt4 book ai didi

python - 将多个列表一一组合

转载 作者:行者123 更新时间:2023-11-28 21:56:37 25 4
gpt4 key购买 nike

我有 3 个列表,我想将我的三个列表组合成另一个列表,其中包含元组或列表,其中混合了这三个列表,如下所示:

years = [2012,2013,2011,2014,2015]
sessions = ["AC", "AB"]
periods = ["I", "II", "III"]

我想知道是否有一个函数或者什么是最 Python 的方法来做下一步:

result = function(years,sessions,periods)
print result

## [(2012, "AC", "I"), (2012, "AC", "II"), (2012, "AC", "III"), (2012, "AB", "I")] and so on

最佳答案

您可以使用 itertools.product()

>>> years = [2012,2013,2011,2014,2015]
>>> sessions = ["AC", "AB"]
>>> periods = ["I", "II", "III"]
>>>
>>> from itertools import product
>>>
>>> list(product(years, sessions, periods))
[(2012, 'AC', 'I'), (2012, 'AC', 'II'), (2012, 'AC', 'III'), (2012, 'AB', 'I'), (2012, 'AB', 'II'), (2012, 'AB', 'III'), (2013, 'AC', 'I'), (2013, 'AC', 'II'), (2013, 'AC', 'III'), (2013, 'AB', 'I'), (2013, 'AB', 'II'), (2013, 'AB', 'III'), (2011, 'AC', 'I'), (2011, 'AC', 'II'), (2011, 'AC', 'III'), (2011, 'AB', 'I'), (2011, 'AB', 'II'), (2011, 'AB', 'III'), (2014, 'AC', 'I'), (2014, 'AC', 'II'), (2014, 'AC', 'III'), (2014, 'AB', 'I'), (2014, 'AB', 'II'), (2014, 'AB', 'III'), (2015, 'AC', 'I'), (2015, 'AC', 'II'), (2015, 'AC', 'III'), (2015, 'AB', 'I'), (2015, 'AB', 'II'), (2015, 'AB', 'III')]

请注意,product() 返回一个可迭代对象;出于演示目的,我刚刚将其转换为上面的列表,但除非您确实需要列表,否则不应这样做。

关于python - 将多个列表一一组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20984422/

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