【问题标题】:How to improve this List Comprehensions?如何改进此列表理解?
【发布时间】:2020-04-25 14:16:42
【问题描述】:

我想知道我可以改进我的 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]])

如您所见,该程序生成了所有三种元素组合。 这个程序中有类似的部分,如for a in [x, y],可以写得更短吗?

[已编辑]

我只想使用标准库和 numpy 库。

输入应该是任何值,例如 x=3、y=8。

【问题讨论】:

标签: python numpy list-comprehension


【解决方案1】:

使用itertools.product:

from itertools import product

# ...
np.array(list(product((x, y), repeat=3)))

【讨论】:

  • 老实说,我不确定这是否会大大提高性能,因为您仍然执行 list(product(...)) 即循环理解。
  • 性能从来都不是问题。即使numpy.array 接受任何可迭代对象,它也必须对其进行迭代以创建数组。
  • 但是很抱歉我应该只使用标准库和numpy库,但我无法指定它。
  • 我错误地认为itertools不在标准python库中,但确实如此。所以,现在使用 itertools 可能是最简单的方法了。
【解决方案2】:

基于Junkrat 建议的类似问题,我提出了这个想法。 (但这并不简单。)

import numpy as np
x=1
y=2
a = np.array(np.meshgrid([x, y], [x, y], [x, y]))   
a = np.rollaxis(a, 0, 4)         
a = a.reshape((2*2*2, 3))  

【讨论】:

    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多