g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
'10.000'
和'10'
是字符串
如何转换为以下格式,字符串为浮点数
预期
[('Books', 10.000),('Pen', 10),('test', 'a')]
10.000
和10
是浮点数,a
必须是字符串
newresult = []
for x in result:
if x.isalpha():
newresult.append(x)
elif x.isdigit():
newresult.append(int(x))
else:
newresult.append(float(x))
print(newresult)
我收到错误消息AttributeError: 'tuple' object has no attribute 'isalpha'
答案 0 :(得分:4)
包含'a'
值(即不可转换为浮点的值),您可以依靠on this answer:
def tofloat(price):
try: return float(price)
except ValueError: return price #we do this when price is not convertable to float
之后,继续进行列表理解:
result = [(item, tofloat(price)) for item, price in g]
result
将是:
[('Books', 10.0), ('Pen', 10.0), ('test', 'a')]
float
10和10.000之间没有区别,因此,如果您希望10和10.000以不同的方式出现,则应将其保留为字符串。
对评论的反思
要检查数值是否为float
而不是int
,我们可以这样做:
print([type(number) for item, number in result])
给出输出:
[<class 'float'>, <class 'float'>, <class 'str'>]
根据需要。
有here的笔记本。
答案 1 :(得分:4)
您的代码有问题,因为您使用的x是元组。您提供的列表的元素是元组类型(String,String),因此您需要在元组的元素上再进行一次迭代。我已将您的代码修改为:
newresult = []
for tuple in result:
temp = []
for x in tuple:
if x.isalpha():
temp.append(x)
elif x.isdigit():
temp.append(int(x))
else:
temp.append(float(x))
newresult.append((temp[0],temp[1]))
print(newresult)
我已经测试过代码:
//input
result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
//output
[('Books', 10.0), ('Pen', 10), ('test', 'a')]
答案 2 :(得分:3)
您需要在每个元组中使用正确的值:
for first_value, second_value in result:
if isinstance(second_value, int):
...
else isinstance(second_value, float):
...
但是不清楚您要完成什么。
答案 3 :(得分:1)
data = [('Books', '10.000'),('Pen', 10)]
print([(a,float(b)) for a,b in data])
这可以帮助循环遍历,并将您在元组中的第二项转换为浮点数
答案 4 :(得分:1)
10,000个转换的数字到底是多少?有2个选项。 10.0或10000.0
在涉及此信件的情况下将不起作用。
参考数据
data = [('Books', '10.000'),('Pen', 10)]
步骤:10000.0
print([(key,float(str(value).replace('.',''))) for key, value in data])
# [('Books', 10000.0), ('Pen', 10.0)]
步:10.0 这已经在上面给出了。但是,请允许我记录一下以避免混淆。
print([(key, float(str(value))) for key, value in data])
# [('Books', 10.0), ('Pen', 10.0)]
答案 5 :(得分:1)
您当前的方法尝试在tuple而不是字符串上使用.isalpha()函数。错误提示您该元组对象没有内置的isalpha()函数。
使用您的方法,您需要解耦元组,以便您可以检查每个元组中的字符串,然后运行逻辑。在代码中,我将检查逻辑抽象到一个函数中,以尝试更清楚地表明您需要为列表中的每个元组运行两次。
def convert_to_proper_type(value):
if value.isalpha():
value = str(value)
elif value.isdigit():
value = int(value)
else:
value = float(value)
return value
result = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
newresult = []
for (value_one, value_two) in result:
# If all chars in both are alphabets
value_one = convert_to_proper_type(value_one)
value_two = convert_to_proper_type(value_two)
newresult.append((value_one, value_two))
print(newresult)
# [('Books', 10.0), ('Pen', 10), ('test', 'a')]
答案 6 :(得分:0)
我会尝试以下操作:
g = [('Books', float('10.000')),('Pen', float('10')),('test', 'a')]
答案 7 :(得分:0)
尝试一下
list_ = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
def fix_list(list_):
def check_and_convert(val_1, val_2):
try:
return val_1, float(val_2)
except:
return val_1, val_2
ret_list = []
for val_1, val_2 in list_:
ret_list.append(check_and_convert(val_1, val_2))
return ret_list
print(fix_list(list_))
# >>> [('Books', 10.0), ('Pen', 10.0), ('test', 'a')]
答案 8 :(得分:0)
# Helper Function check if string is a number
def is_number(n:str):
try:
float(n)
except ValueError:
return False
return True
# Filter the list of numbers using the following
>>> g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
>>> [float(char) if is_number(char) else char for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0, 'a']
>>> # If only numbers are needed
>>> [float(char) if is_number(char) for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0]
答案 9 :(得分:0)
有很多方法可以制定可行的解决方案,但我认为最好的办法就是更正您的解决方案
在您的代码中
for x in result:
x的值是:('Books','10 .000'),('Pen','10'),('test','a') 所以我们需要修改条件以查看每个元组的第二个元素
newresult = []
for x in result:
if x[1].isalpha():
newresult.append(x)
elif x[1].isdigit():
newresult.append((x[0],int(x[1])))
else:
newresult.append((x[0],float(x[1])))
print(newresult)