【问题标题】:Generate Python dictionary from combination of lists从列表组合生成 Python 字典
【发布时间】:2020-01-28 19:23:09
【问题描述】:

我已尝试解决我的问题,但无法解决。

我有三个 Python 列表:

atr = ['a','b','c']
m = ['h','i','j']
func = ['x','y','z']

我的问题是根据这三个列表的组合生成一个 Python 字典:

想要的输出:

py_dict = {
    'a': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')],
    'b': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')],
    'c': [('x','h'), ('x','i'), ('x','j'), ('y','h'), ('y','i'), ('y','j'),('z','h'), ('z','i'), ('z','j')]
}

【问题讨论】:

    标签: python pandas list dictionary combinations


    【解决方案1】:

    你可以使用itertools.product:

    import itertools
    atr = ['a','b','c']
    m = ['h','i','j']
    func = ['x','y','z']
    prod = list(itertools.product(func, m))
    result = {i:prod for i in atr}
    

    输出:

    {'a': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'b': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'c': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')]}
    

    【讨论】:

    • 谢谢老哥,天哪,我只知道Python有没有这种功能。
    猜你喜欢
    • 2021-01-23
    • 2019-05-09
    • 1970-01-01
    • 2014-05-17
    • 2018-09-06
    • 1970-01-01
    • 2019-05-05
    • 2013-02-19
    • 2018-01-11
    相关资源
    最近更新 更多