gpt4 book ai didi

python - 从列表中获取特定长度的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:49 32 4
gpt4 key购买 nike

我追求的是这样的:

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']

关于python - 从列表中获取特定长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22362736/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com