JBW*_*ore 6 python numpy list set
我有两个清单.
第一个列表已经排序(通过其他一些标准),因此列表中较早的列表越好.
sortedList = ['200', '050', '202', '203', '206', '205', '049', '047', '042', '041', '043', '044', '046', '045', '210', '211', '306', '302', '308', '309', '311', '310', '221', '220', '213', '212']
Run Code Online (Sandbox Code Playgroud)
第二个列表是允许值列表:
allowedList = ['001','002','003','004','005','006','007','008','009','010','203','204','205','206','207','212','213','215','216']
Run Code Online (Sandbox Code Playgroud)
我想选择allowedList中存在的最高排序值,而我只是想出这样做的愚蠢方法.这样的事情:
import numpy as np
temp = []
for x in allowedList:
temp.append(sortedList.index(x))
np.min(temp)
Run Code Online (Sandbox Code Playgroud)
必须有一个比这更好的方法.有任何想法吗?
使用已经排序的事实的解决方案allowedlist可能更有效(并且使用 a set,它们当然是 - 线性时间与二次),但仅为了完整性,您现有的解决方案可以大大缩短,并消除临时列表:
min(allowedList, key=sortedList.index)
Run Code Online (Sandbox Code Playgroud)
它使用 Python 的内置min函数,而不是 numpy 中的函数 -np.min主要仅在将它们与 numpy 数组一起使用时才有用;使用列表时不需要它。
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |