【发布时间】:2021-09-03 11:17:40
【问题描述】:
为了缩短执行时间,我用 np.where() 中的条件替换了一个理解列表。它在值匹配的地方工作正常,但我希望有一个条件,即字符串中的值不相等:
import numpy as np
currencies = np.array(["USD","NZL","EUR","KWR"])
currencie = [x for x in list(currencies) if x in "USDKLR EUR"]
#returns ["USD","EUR"]
#What works:
currencie = currencies[np.where(currencies == "EUR")]
#returns ["EUR"]
我想要的是 in 条件,但使用 np.where 或 numpy 函数,没有列表处理。
currencie = currencies[np.where(currencies in "USDKLR EUR")]
【问题讨论】:
-
我已经更新了我的问题。很抱歉造成混乱。
-
where仅与其条件参数一样好。它不是一个迭代器。它只是找到 True 元素。虽然 numpy 有一组字符串函数,但它们使用字符串方法并且并不比列表理解快。