仅返回数字+美元的字符串的总值

2024-10-03 06:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我只需要在['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

Tags: 字符串intrueforstringreturnifdef
3条回答

这里需要纠正的三件事:

  1. 正如DeepSpace所说,$取消了将字符串解释为浮点的资格,因此需要首先删除它。这里.replace()方法很有用

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

  3. for循环中的条件应该包含.,以便将它们包含在要包含的浮点中,否则示例列表将返回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

这应该做到:

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中,检查列表是否为空并不是惯用的方法。还可以简化表达式,检查字符串是否为数字。如果你想要一行,你可以写:

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

相关问题 更多 >