![](/img/trans.png)
[英](Python, Selenium) Is it possible to get text list only if the attribute meets criteria?
[英]Get percentage of a list that meets criteria
當然,這與循環和其他丑陋的,非Python的事情非常容易。 本質上,是否存在一種方法(最好是單線方法),該方法將遍歷列表並獲得持有財產的百分比? 例如,
def predicate(x):
#Returns if x is even
return x % 2 == 0
#Performed on [1,2,3,4]
50
#Performed on [5,3,7,2]
25
是否有捷徑可尋?
計算與sum()
匹配的內容,然后除以長度,再乘以100
def percentage(L, predicate):
return (sum(1.0 for v in L if predicate(v)) / len(L)) * 100
沒有創建額外的列表對象來產生該值,從而產生了恆定的存儲算法。
演示:
>>> def percentage(L, predicate):
... return (sum(1.0 for v in L if predicate(v)) / len(L)) * 100
...
>>> def property(x):
... #Returns if x is even
... return x % 2 == 0
...
>>> percentage([1,2,3,4], property)
50.0
>>> percentage([5,3,7,2], property)
25.0
這個怎么樣?
100 * ( len([x for x in l if property(x)]) / len(l) )
還有另一個利用True
為1
和False
為0
替代方法:
sum(map(property, your_list), 0.0) / len(your_list) * 100
>>> l = [1, 2, 3, 4]
>>> len(filter(property, l)) * 100 / len(l)
50
>>> l = [5, 3, 7, 2]
>>> len(filter(property, l)) * 100 / len(l)
25
從Need取得結果的快速方法可以在一次通過中對一個可迭代對象進行計數和求和
我們得到一個能夠采用任何可迭代的答案,包括任何生成器表達式。 由於通常不能占用生成器的長度,因此這可能很有用。
def predicate(x):
#Returns if x is even
return x % 2 == 0
def percentage(iterable, conditional):
import itertools
from collections import deque
it = (1.0 if conditional(i) else 0.0 for i in iterable)
res = deque(enumerate(itertools.accumulate(it), 1), maxlen=1)
if len(res) == 0:
return 0.0
return 100.0 * res[0][1]/res[0][0]
L1 = [1,2,3,4]
percentage(L1, predicate)
# 50.0
L2 = [5,3,7,2]
percentage(L2, predicate)
這是一種超快速的東西,可以在Python 2和3中使用,可以處理空列表,並且是單線的:
def predicate(x):
return x % 2 == 0 # x even?
for lst in [1,2,3,4], [5,3,7,2], []:
print(0.0 if not lst else sum(map(predicate, lst), 0.0) / len(lst) * 100)
輸出:
50.0
25.0
0.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.