我需要的就是这样的:
list1 = ["well", "455", "antifederalist", "mooooooo"]
由于字符数目的原因,从列表中提取"455"
。
next()
方法来实现:
>>> list1 = ["well", "455", "antifederalist", "mooooooo"]
>>>
>>> next(s for s in list1 if len(s) == 3)
'455'
next()
函数还允许您指定一个“默认”值,如果列表中没有长度为3的字符串,则返回该值。例如,在这种情况下返回None
:
>>> list1 = ["well", "antifederalist", "mooooooo"]
>>>
>>> print next((s for s in list1 if len(s) == 3), None)
None
(我使用了显式的 print
,因为在交互模式下,默认情况下不会打印 None
。)
如果你想要长度为 3 的所有字符串,你可以很容易地将上面的方法转换成列表推导:
>>> [s for s in list1 if len(s) == 3]
['455']
filter(lambda s: len(s) == 3, list1)
如果你想从列表中提取所有长度大于某个值的项:
list2 = [string for string in list1 if len(string) >= num_chars]
b
仍然比a
快大约0.5秒。 - Adam Smith