3 回答

TA贡献1804条经验 获得超7个赞
您可以使用生成器表达式过滤非数字:
arr = [5,3,6,"-",3,"-",4,"-"]
result = min(e for e in arr if isinstance(e, int))
print(result)
输出
3

TA贡献1777条经验 获得超10个赞
这是一种直接使用自定义函数max和min内置函数的方法key:
arr = [5,3,6,"-",3,"-",4,"-"]
max(arr, key=lambda x: (isinstance(x,int), x))
# 6
并且对于min:
min(arr, key=lambda x: (not isinstance(x,int), x))
# 3
细节
对于 min,将以下列表推导式视为与 应用的转换的“等效” key:
sorted([(not isinstance(x,int), x) for x in arr])
[(False, 3),
(False, 3),
(False, 4),
(False, 5),
(False, 6),
(True, '-'),
(True, '-'),
(True, '-')]
所以min将是最低的元组,即(0,3)。
对于max,最高将是(1,6):
sorted([(isinstance(x,int), x) for x in arr])
[(False, '-'),
(False, '-'),
(False, '-'),
(True, 3),
(True, 3),
(True, 4),
(True, 5),
(True, 6)]

TA贡献1909条经验 获得超7个赞
您可以转换list为set加速计算:
min(i for i in set(arr) if isinstance(i, int))
基准:
setup = "arr = [5, 3, 6,'-', 3,'-', 4, '-'] * 1000"
solution1 = "min(i for i in set(arr) if isinstance(i, int))"
solution3 = "min(e for e in arr if isinstance(e, int))"
solution2 = "min(arr, key=lambda x: (not isinstance(x,int), x))"
print(timeit.timeit(setup=setup, stmt=solution1, number=10000))
print(timeit.timeit(setup=setup, stmt=solution2, number=10000))
print(timeit.timeit(setup=setup, stmt=solution3, number=10000))
输出:
1.0895615029
13.389633473
22.653398585
如果您只有一种类型的字符串:
min(set(arr) - {'-'})
添加回答
举报