gpt4 book ai didi

python - 去掉string中的一个char,然后用字典做key match

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:26 25 4
gpt4 key购买 nike

我想编写一个函数,通过使用 map 和 reduce 将字符串转换为 float 。 (这里没有 int() )。到目前为止,这是我的代码:

from functools import reduce

def str2float(s):
def char2number(s):
s = s.replace('.', '')
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] #here i try to get pure numbers

def find_digt(s):
return (len(s) - s.find('.') - 1) if ',' in s else 0

return reduce(lambda x, y: (10 * x + y), (map(char2number, s))) / pow(10, find_digt(s))


print(str2float('1456.124'))

所以在这之后,我得到一个错误:

return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[sn]  # [s] is the [key]
KeyError: ''

这意味着 '' 不在字典中。我做了一些测试:

s = '1234.456'
s = s.replace(',', '')
print('' in s) #True

那么现在的问题是,一旦

s = s.replace('.', '')

'.'替换为'',它没有清除'。'在字符串中。

我想知道这里发生了什么。清除字符串中字符的正确方法是什么,因为它是不可变的。

最佳答案

问题是您在 未更改 输入字符串上使用 map 进行迭代,因为您只删除了 char2number< 中的 ./功能。在函数之外,替换没有发生。

我会建议找到位置并立即替换它:

from functools import reduce

def str2float(s):
pos_decimal_point = (len(s) - s.find('.') - 1) if '.' in s else 0
s = s.replace('.', '')

def char2number(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] #here i try to get pure numbers

return reduce(lambda x, y: (10 * x + y),
(map(char2number, s))) / pow(10, pos_decimal_point)


print(str2float('1456.124'))

关于python - 去掉string中的一个char,然后用字典做key match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44014005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com