[英]How to find the largest number in a list that is not X number?
假設我有兩個列表:
x = [6,5,5,4]
z = [5,5,4,3]
我想在每個列表中找到不是5
的最大數字。
所以x
的最大值是6
而z
的最大值是4
。
我的想法:
5
,然后找到最大值。 或者5
是最大值,則返回第二高的數字。 如果5
不是最大值,則返回最大值。你會用另一種方式解決這個問題嗎?
檢查這個。
x = [6,5,5,4]
z = [5,5,4,3]
print(max(e for e in x if e!=5))
print(max(f for f in z if f!=5))
#!/usr/bin/env python
def max_excluding(it, num):
try:
return max(filter(lambda x: x != num, it))
except ValueError:
return
for x in [[6,5,5,4], [5,5,4,3], [5], [1]]:
print(max_excluding(x, 5))
Output:
6
4
None
1
我發現迭代器上的過濾器比代碼的關鍵部分隱藏在行尾附近的列表推導更容易推理。
然而,我驚訝地發現它導致代碼花費了將近 25%-30% 的時間:
import timeit
cases = {
'comprehension': {
'setup': "\n".join([
'import random',
'X = [int(random.randint(0, 10)) for _ in range(1000000)]',
]),
'stmt': 'max([x for x in X if x != 5])',
},
'filter': {
'setup': "\n".join([
'import random',
'X = [int(random.randint(0, 10)) for _ in range(1000000)]',
]),
'stmt': 'max(filter(lambda x: x != 5, X))',
},
}
for case, code in cases.items():
print(case)
print(timeit.timeit(**code, number=100))
采樣時序 output:
comprehension
11.6845581
filter
14.393007899999999
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.