将元组列表中的元素转换为浮点数的Python程序
给定一个元组列表,将所有可能的可转换元素转换为浮点数。
Input : test_list = [(“3”, “Gfg”), (“1”, “26.45”)]
Output : [(3.0, ‘Gfg’), (1.0, 26.45)]
Explanation : Numerical strings converted to floats.
Input : test_list = [(“3”, “Gfg”)]
Output : [(3.0, ‘Gfg’)]
Explanation : Numerical strings converted to floats.
方法 #1:使用循环 + isalpha() + float()
在这里,我们使用循环来迭代所有元组,使用 isalpha() 检查字母表,它无法转换为浮点数,其余元素使用 float() 进行转换。
Python3
# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using loop + isalpha() + float
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
# printing original list
print("The original list is : " + str(test_list))
res = []
for tup in test_list:
temp = []
for ele in tup:
# check for string
if ele.isalpha():
temp.append(ele)
else:
# convert to float
temp.append(float(ele))
res.append((temp[0],temp[1]))
# printing result
print("The converted list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using loop + isalpha() + float
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
# printing original list
print("The original list is : " + str(test_list))
res = []
for tup in test_list:
# list comprehension to check for each case
temp = [ele if ele.isalpha() else float(ele) for ele in tup]
res.append((temp[0],temp[1]))
# printing result
print("The converted list : " + str(res))
输出:
The original list is : [(‘3’, ‘Gfg’), (‘1’, ‘26.45’), (‘7.32’, ‘8’), (‘Gfg’, ‘8’)]
The converted list : [(3.0, ‘Gfg’), (1.0, 26.45), (7.32, 8.0), (‘Gfg’, 8.0)]
方法 #2:使用循环 + isalpha() + float() +列表理解
在这里,我们使用列表理解来执行迭代内部元组的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using loop + isalpha() + float
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
# printing original list
print("The original list is : " + str(test_list))
res = []
for tup in test_list:
# list comprehension to check for each case
temp = [ele if ele.isalpha() else float(ele) for ele in tup]
res.append((temp[0],temp[1]))
# printing result
print("The converted list : " + str(res))
输出:
The original list is : [(‘3’, ‘Gfg’), (‘1’, ‘26.45’), (‘7.32’, ‘8’), (‘Gfg’, ‘8’)]
The converted list : [(3.0, ‘Gfg’), (1.0, 26.45), (7.32, 8.0), (‘Gfg’, 8.0)]