Python:具有多个条件的列表理解
我有: 我只想返回一个浮点数(1.52) 我试过:Python:具有多个条件的列表理解,python,Python,我有: 我只想返回一个浮点数(1.52) 我试过: s= 'Lot Size: 1.52 acres' 我怎样才能让它工作呢?试试看 >>> o =[s for s in str.split('') if s.isdigit() if s=='.'] >>> >>>o >>>[] 这将为o分配msg中可解释为浮动的“单词”列表: o = float(s.split(':')[1].split('acres')[0].
s= 'Lot Size: 1.52 acres'
我怎样才能让它工作呢?试试看
>>> o =[s for s in str.split('') if s.isdigit() if s=='.']
>>>
>>>o
>>>[]
这将为
o
分配msg
中可解释为浮动的“单词”列表:
o = float(s.split(':')[1].split('acres')[0].strip())
您可以使用一个单独的条件并按照原始格式(使用python 3.6.8)尝试以下操作: 多条件语法:
def isFloat(n):
try:
return float(n)
except:
return None
o = list(filter(isFloat,msg.split()))
[ x for x in x.do() if 'x' in x OR/AND if x == 1]
s = 'Lot Size: 1.52 acres'
o = [s for s in s.split(' ') if '.' in s]
print(o[0])
示例:
def isFloat(n):
try:
return float(n)
except:
return None
o = list(filter(isFloat,msg.split()))
[ x for x in x.do() if 'x' in x OR/AND if x == 1]
s = 'Lot Size: 1.52 acres'
o = [s for s in s.split(' ') if '.' in s]
print(o[0])
输出:
def isFloat(n):
try:
return float(n)
except:
return None
o = list(filter(isFloat,msg.split()))
[ x for x in x.do() if 'x' in x OR/AND if x == 1]
s = 'Lot Size: 1.52 acres'
o = [s for s in s.split(' ') if '.' in s]
print(o[0])
另一种方法是使用正则表达式:
1.52
这将为您提供:
import re
s='Lot Size: 1.52 acres'
result = float(re.findall("[0-9]+\.[0-9]+", s)[0])
print(result)
或者,如果您希望得到一个浮动列表:
1.52
为什么最后需要一个列表?您希望
str.split(“”)
做什么?当我尝试运行您拥有的内容时,会得到ValueError:empty separator
。这是Python 2吗?使用正则表达式吗?为什么你在iOS上阻止我复制/粘贴?你对这个字符串的结构做了很多假设。如果我们要假设它是第三项o=float(s.split()[2])
。请注意,这对没有精确小数点的“数字”不起作用。说得好,需要针对更大范围的输入进行调整:)@scotthunter这只起作用,因为您没有调用s.isdigit
——请注意缺少括号。将其更改为s.isdigit()
,失败原因是'1.52'。