【问题标题】:return total value of only strings with a number + dollar仅返回带有数字 + 美元的字符串的总值
【发布时间】:2021-06-02 11:45:57
【问题描述】:

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

【问题讨论】:

  • isnumber 并没有真正做到你认为的那样(提示:'$' 不能转换为 float

标签: python string price shop dollar-sign


【解决方案1】:

应该这样做:

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

输出:

22.55$

一步一步:

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

【讨论】:

    【解决方案2】:

    首先,您应该使用字符串的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 处于 相同 的缩进级别;现在它只返回第一次迭代后的数量,跳过其余的列表元素。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多