生成对的pythonic方式 [英] The pythonic way to generate pairs

查看:63
本文介绍了生成对的pythonic方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要类似下面的代码,但使用 pythonic样式或使用标准库:

I want something like code below, but "pythonic" style or using standard library:

def combinations(a,b):
    for i in a:
        for j in b:
             yield(i,j)


推荐答案

从组合意义上讲,这些并不是真正的组合,而是来自 a的笛卡尔积的元素 b 。标准库中用于生成这些对的函数是 itertools.product()

These are not really "combinations" in the sense of combinatorics, these are rather elements from the cartesian product of a and b. The function in the standard library to generate these pairs is itertools.product():

for i, j in itertools.product(a, b):
    # whatever

这篇关于生成对的pythonic方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆