我只需要在['10$'、'sock'、'12.55$'、'pizza11'中返回包含数字+美元的字符串的总值,如'12.55$'。例如,此列表应返回22.55美元(带美元符号)
所有其他字符串都没有值。我创建了一个函数isnumber:
def isnumber(string):
try:
float(string)
except:
return False
return True
还有这个,但它不起作用:
def value_liste(liste):
amount = 0
if liste == []:
return 0.0
for string in liste:
if isnumber(string) == True and string[-1:] == '$':
amount += float("".join(d for d in string if d.isdigit()))
return amount
这里需要纠正的三件事:
正如DeepSpace所说,
$
取消了将字符串解释为浮点的资格,因此需要首先删除它。这里.replace()
方法很有用注意你的缩进!Python对此很挑剔。如果函数声明后没有缩进,Python将抛出一个错误。另外,循环
for
之后的返回语句应该与单词for
处于相同的缩进级别;现在它只返回第一次迭代后的数量,跳过其余的列表元素for
循环中的条件应该包含.
,以便将它们包含在要包含的浮点中,否则示例列表将返回1265.0
总之,以下是一个更正版本:
这应该做到:
输出:
逐步:
首先,您应该使用字符串的
rstrip()
方法,该方法删除字符串末尾的字符,如下所示:然后,如果我正确理解了第二段代码(因为格式有问题),结果如下所示:
在Python中,检查列表是否为空并不是惯用的方法。还可以简化表达式,检查字符串是否为数字。如果你想要一行,你可以写:
相关问题 更多 >
编程相关推荐