如何提高清单理解力?

我不知道我可以将我的python代码缩短一些。 我只使用标准库和numpy库。 这是代码。

import numpy as np
x=1
y=2
np.array([(a,b,c) for a in [x,y] for b in [x,y] for c in [x,y]])

As you can see, this program produces all three combinations of elements. There is a similar part in this program like for a in [x, y] and can it be shorter?

评论
  • SayNo
    SayNo 回复

    Use itertools.product:

    from itertools import product
    
    # ...
    np.array(list(product((x, y), repeat=3)))
    
  • 情断心却相
    情断心却相 回复
    from itertools import permutations as c
    list(c([1,2,3], 3))
    # [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]