![](/img/trans.png)
[英]Using lambdas with iteration values of for loop inside of that for loop in python
[英]Lambdas Python for loop
如果某些元素是非數字的,我想在循環內部使用lambdas返回:
strs = ['1234', 'hello', '6787']
我可以使用for
循環並遍歷每個元素:
for elem in strs:
並檢查elem.islpha()
。
但是,有沒有辦法使用lambdas
和for
循環來返回單詞"hello"
?
試試這個,使用列表理解很容易:
lst = ['1234', 'hello', '6787']
[x for x in lst if x.isalpha()]
=> ['hello']
或者如果你肯定想要使用lambda:
filter(lambda x: x.isalpha(), lst)
=> ['hello']
請注意,在for
循環中很少使用lambdas進行過濾,這不是慣用的。 從列表中過濾元素的方法是使用列表推導,生成器表達式或(不太推薦) filter()
內置函數。
首先,習慣於列表理解:
>>> strs = ['1234', 'hello', '6787']
>>> [s for s in strs if s.isalpha()]
['hello']
它們是最具適應性的,在大多數情況下,是最易讀的方式。 那你為什么要用map
? map
很快,很好尋找簡單的案例:
>>> map(str.upper, strs)
['1234', 'HELLO', '6787']
但是你必須使用lambda
的實例 ,地圖變得丑陋而緩慢 。 此規則也適用於filter
。
In [1]: strs = ['1234', 'hello', '6787']
In [2]: %timeit map(lambda s: s[0] if s.isalpha() else s, strs)
1000000 loops, best of 3: 1.48 us per loop
In [3]: %timeit [s[0] if s.isalpha() else s for s in strs]
1000000 loops, best of 3: 799 ns per loop
很多人都建議過
>>> filter(lambda s: s.isalpha(), strs)
['hello']
但請記住lambda s: s.isalpha()
只是lambda s: s.isalpha()
字符串類的方法)的str.isalpha
。
>>> filter(str.isalpha, strs)
['hello']
這使得在這里使用filter
變得干凈和快速,但是一旦涉及到lambda
,就要記住它的后果。
Python 2.x的實現細節
不幸的是,python 2.x有兩種不同的字符串類型(在python 3中只有str
是unicode) str
和unicode
。 因此使用str.isalpha
的清潔解決方案將不起作用。 您可以簡單地將其更改為unicode.isalpha
但如果您正在混合unicode
和str
,則需要交叉兼容的東西。
一種替代方法是使用methodcaller
>>> strs = [u'\n', u'test', u'\t']
>>> from operator import methodcaller
>>> filter(methodcaller('isalpha'), strs)
[u'test']
但這並不是非常簡單,這就是為什么只使用列表推導來避免這種麻煩是很好的。
>>> [s for s in strs if s.isalpha()]
[u'test']
如果你真的需要使用lambda
,或者你正在學習函數式編程,你可以使用filter
:
>>> filter(lambda x:x.isalpha(), ['123','hello','456'])
['hello']
在循環中使用lambda在你的上下文中是沒有意義的,因為你可以直接調用x.isalpha()
這可能就是你要找的東西。 您不能顯式使用for
循環,但可以使用生成器表達式:
check_isalpha = lambda lst: (elem for elem in lst if elem.isalpha())[0]
如果你想要的是從列表中提取非數字項,我認為不需要使用lambda。
alphas = [item for item in strs if item.isalpha()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.