return 只有数字 + 美元的字符串的总价值

return total value of only strings with a number + dollar

我需要return ['10$', 'sock', '12.55$', 'pizza11']。例如,此列表应 return 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

应该这样做:

l = ['10$', 'sock', '12.55$', 'pizza11']
answer = str(sum([float(i.replace('$','')) for i in l if i.endswith('$')])) + '$'
print(answer)

输出:

22.55$

一步一步:

  • 只取列表中以“$”结尾的元素
  • 从字符串中去除 '$' 并将其转换为浮点数
  • 对这些值求和。
  • 将结果转为字符串。
  • 在字符串末尾添加'$'

首先,您应该使用字符串的 rstrip() 方法,它删除字符串末尾的字符,如下所示:

def is_number(string):
    try:
        float(string.rstrip('$'))
    except:
        return False
    return True

那么,如果我正确理解第二段代码(因为格式有问题),结果将是这样的:

def value_liste(liste):
    amount = 0

    if not liste:
        return 0.0

    for string in liste:
        if isnumber(string):
            amount += float(string.rstrip(('$'))
        return amount

像您那样检查列表是否为空在 Python 中不是惯用的。您还可以简化表达式,在其中检查字符串是否为数字。如果你想要oneliner,你可以这样写:

my_list = ['10$', 'sock', '12.55$', 'pizza11']
total = sum(float(el.rstrip('$')) for el in my_list if el.endswith('$'))

3 处需要更正的地方:

  1. 正如 DeepSpace 所说,$ 使字符串无法被解释为浮点数,因此需要先将其删除。 .replace() 方法在这里很有用。

  2. 注意你的缩进! Python 对此很挑剔。如果函数声明后没有缩进,Python 将抛出一个错误。另外,for 循环之后的 return 语句应该与单词 for 处于 相同的 缩进级别;现在它只是 return 第一次迭代后的数量,跳过列表元素的其余部分。

  3. for循环中的条件应该包括.的,以便将它们包含在float中以包含,否则你的示例列表return s 1265.0.

总而言之,这是一个更正后的版本:

def isnumber(string):
    string_no_dollar = string.replace("$", "") # removes all $-signs
    try:
        float(string_no_dollar)
    except:
        return False
    return True


def value_liste(liste):
    # Code is indented after function declaration, as it must always be in Python.
    amount = 0 

    if liste == []:
        return 0.0

    for string in liste:
        if isnumber(string) == True and string[-1:] == '$':
            # Include the "." in the conditional.
            amount += float("".join(d for d in string if d.isdigit() or d == "."))
    # The "return" statement should be indented outside the "for" loop.
    return amount