从列表中获取一定长度的字符串

use*_*828 3 python string list

我所追求的是这样的:

list1 = ["well", "455", "antifederalist", "mooooooo"]
Run Code Online (Sandbox Code Playgroud)

"455"由于字符数量而从列表中拉出的东西.

ars*_*jii 5

您可以使用next()发电机:

>>> list1 = ["well", "455", "antifederalist", "mooooooo"]
>>> 
>>> next(s for s in list1 if len(s) == 3)
'455'
Run Code Online (Sandbox Code Playgroud)

next()如果列表不包含任何长度为3的字符串,还允许您指定要返回的"默认"值.例如,要None在这种情况下返回:

>>> list1 = ["well", "antifederalist", "mooooooo"]
>>> 
>>> print next((s for s in list1 if len(s) == 3), None)
None
Run Code Online (Sandbox Code Playgroud)

(我使用了显式,print因为None在交互模式下默认不打印.)

如果你想要所有长度为3的字符串,你可以轻松地将上面的方法转换为列表理解:

>>> [s for s in list1 if len(s) == 3]
['455']
Run Code Online (Sandbox Code Playgroud)