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

3

我需要的就是这样的:

list1 = ["well", "455", "antifederalist", "mooooooo"]

由于字符数目的原因,从列表中提取"455"

3个回答

5
您可以使用生成器和 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']

@wim 是的,那是一个非常好的观点。我会把它加入到答案中。谢谢! - arshajii
1
@adsmith 我不会期望有太大的差异。你测量了什么时间?我敢打赌,如果你使用更大的列表,时间看起来会不那么不同。 - arshajii
b仍然比a快大约0.5秒。 - Adam Smith
有趣的时间。如果“命中”在一个长列表的末尾,会怎样呢? - wim
1
@adsmith 所以它们本质上是相同的。 - arshajii
显示剩余9条评论

1
filter(lambda s: len(s) == 3, list1)

0

如果你想从列表中提取所有长度大于某个值的项:

 list2 = [string for string in list1 if len(string) >= num_chars]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接