Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中获取特定长度的字符串_Python_String_List - Fatal编程技术网

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

Python 从列表中获取特定长度的字符串,python,string,list,Python,String,List,我所追求的是这样的: list1 = ["well", "455", "antifederalist", "mooooooo"] 由于字符数的原因,从列表中提取的内容。可以与生成器一起使用: >>> list1 = ["well", "455", "antifederalist", "mooooooo"] >>> >>> next(s for s in list1 if len(s) == 3) '455' next()还允许您指定在列

我所追求的是这样的:

list1 = ["well", "455", "antifederalist", "mooooooo"]
由于字符数的原因,从列表中提取的内容。

可以与生成器一起使用:

>>> 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
s在交互模式下默认不打印。)

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

>>> [s for s in list1 if len(s) == 3]
['455']

如果您希望从列表中拉出超过某个长度的所有项目:

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

对于失败模式,如果不希望它引发StopIteration,也可以指定一个默认值。@wim是的,这是一个很好的观点。我将把它添加到答案中。谢谢我想知道这是如何叠加到只定义一个函数,该函数使用
for
循环运行
list1
,并返回
len
为3的第一个值?在
timeit
中进行的快速测试表明,速度要快得多,但是……@adsmith我不认为会有太大的差异。你测量了几次?我敢打赌,如果你使用一个更大的列表,时间看起来就不会那么不同了。@adsmith,所以它们基本上是一样的。
filter(lambda s: len(s) == 3, list1)