use*_*828 3 python string list
我所追求的是这样的:
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']
| 归档时间: | 
 | 
| 查看次数: | 537 次 | 
| 最近记录: |