【问题标题】:How to convert strings with positive/negative integers and floats in Python如何在 Python 中用正/负整数和浮点数转换字符串
【发布时间】:2021-02-24 23:57:40
【问题描述】:

我的代码可以根据字符串本身将字符串转换为整数或浮点数。

def convert_data(data: List[List[str]]) -> None:
   for sublist in data: #Accesses each element in data
      for index, element in enumerate(sublist): 
         if element.isnumeric(): #If element is a number, check to see if it can be an int
            sublist[index] = int(element) #Convert to an int
   
         elif element.replace('.', '').isnumeric(): #If element is a number, check to see if it can be a float
            sublist[index] = float(element) #convert to a float
         
         else:
            sublist[index] = sublist[index] #If it isn't a number, return the string as it is

our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]

convert_data(our_data)

函数运行后,our_data 应该是:

[['no'], [-123], [5.6, 3.2], [3, 4, -5]]

但是,我得到:

[['no'], ['-123'], ['+5.6', 3.2], [3.0, '+4', '-5.0']]

我需要这样做,以便它将带有“+”或“-”的任何内容转换为整数/浮点数,而不是将其作为字符串返回。我该怎么做?

如果您认为我的代码混乱,我深表歉意,我只是在快速尝试解决我遇到的这个问题。感谢您的帮助!

【问题讨论】:

  • eval() 可以解决这个问题

标签: python python-3.x list integer


【解决方案1】:

原因

'+''-' 不是 is_numeric() - 如果您想保持自己的方法,您需要手动处理

往下看,以更短、更好的方式来做同样的事情。

修复

def convert_data(data: List[List[str]]) -> None:
   for sublist in data: #Accesses each element in data
      for index, element in enumerate(sublist):
         sign = 1 
         # parse sign for later multiplication
         if element.startswith("+"):
             element = element[1:]
         elif element.startswith("-"):
             sign = -1
             element = element[1:]

         if element.isnumeric():  #   '12345'
            sublist[index] = sign * int(element)  
   
         elif element.replace('.', '').isnumeric():  # '123.45' but also '12.3.2020'
            sublist[index] = sign * float(element)   # convert to a float
         
         else:
            sublist[index] = sublist[index]          # keep as is

our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]
convert_data(our_data)
print(our_data)  

输出:

[['no'], [-123], [5.6, 3.2], [3.0, 4, -5.0]]

优化和更多pythonic:

def convert_data(data )  :
    for sublist in data: 
        for index, element in enumerate(sublist):
           try:
               element = float(element)
               if element.is_integer():
                   element = int(element)
           except ValueError:
               pass
           sublist[index] = element 

"Ask forgiveness not permission" - explain

【讨论】:

  • 次要。在这种情况下它可能是安全的,因为元素已就地修改,但您确实不应该在迭代列表时修改列表。如果代码以for index in range(len(sublist)): 开头,然后是element = sublist[index],我会更高兴。 YMMV。
  • @Frank - 您指的是通过从中删除元素来缩短列表。修改元素保存做 - 没有理由为此使用索引。 Anf 如果你仔细看,assignemt 是使用索引完成的 - 从枚举列表中收集。
  • 是的。不,也许。我相信你,但我真的找不到任何说明这种或另一种方式的文档。如果您知道 Python 官方文档,我将不胜感激。
  • @Frank 逻辑:删除列表元素的问题是你跳过元素 - 你在 3,下一个是 4,但是你删除了 3,所以 4 现在是 3,你的下一个元素将是new 4th(前 5th)因此错误,因为您跳过处理某些值。如果您只是修改值,绝对没有问题。见 f.e. stackoverflow.com/questions/44864393/…
【解决方案2】:

实际上,您不需要处理字符串类型,也不需要处理 sings,因为 float 会为您完成。您可以只使用tryexcept 尝试将字符串转换为浮点数,或者在不可能的情况下返回字符串:

def convert(x):
    try:
        return float(x)
    except:
        return x

our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]
new_data = []
for data in our_data:
    new_data.append(list(map(lambda x: convert(x), data)))

print(new_data)

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多