我只想从输入元素为str的Python list中提取数字
input_in_terminal = "5 43 8 109 32"
input_list = [5, ' ', 43, ' ', 8, ' ', 109, ' ', 32]我如何只提取数字并创建一个列表,如下所示?
extracted_list = [5,43,8,109,32]发布于 2018-06-05 06:41:00
Python 3:
extracted_list = list(filter(lambda x: x != ' ' , input_list))或者,如果您想避免使用多个空格,请检查它是否为整数,并过滤掉任何不是整数的内容。
extracted_list = list(filter(lambda x: isinstance(x,int) , input_list))如果您需要其他类型,如float或complex,您可以这样做:
extracted_list = list(filter(lambda x: isinstance(x,(float,int,complex)) ,input_list))
speed: --- 6.818771362304688e-05 seconds ---或任何数字
import numbers
input_list = [5, ' ', 43, ' ', 8, ' ', 109, ' ', 32, 3.14]
extracted_list = list(filter(lambda x: isinstance(x, numbers.Number) ,input_list))
print (extracted_list)你可以在这里测试它:http://py3.codeskulptor.org/#user301_l6dgnVkb19Or9dN.py
https://stackoverflow.com/questions/50689563
复制相似问题