简体   繁体   English

如何将由整数和浮点数组成的列表中的字符串列表转换为整数和浮点数?

[英]How do I convert a list of strings in a list composed of ints and floats to both ints and floats?

例如,我有列表 ['-1','9','7.8'] 如何将列表转换为 [-1,9,7.8] 而不必在全部转换为浮点数或全部转换为浮点数之间进行选择整数?

You can use list comprehension and ternary operator to do this您可以使用列表理解和三元运算符来执行此操作

lst =['-1','9','7.8']
lst = [float(numStr) if '.' in numStr else int(numStr) for numStr in lst ]

Here 2 simple solutions这里有2个简单的解决方案

# 1 Just convert to float.
print([float(i) for i in ['-1','9','7.8']])


# 2 Check if are dotted
convert = [float(i) if '.' in i else int(i) for i in ['-1','9','7.8']]
print(convert)

The first would work because a integer can be always converted to float.第一个可行,因为整数总是可以转换为浮点数。 But if you really need to have the 2 differentiated then just check if are dotted.但是,如果您真的需要区分 2,那么只需检查是否加点。

**Solution 3 ** **解决方案 3 **

"Ask forgiveness not permission" just try to convert it to a int, if it fails then to a float “请求宽恕而不是许可”只是尝试将其转换为 int,如果失败则为浮点数

def int_float_converter(data):

    converted_data = []
    for d in data:
        val = None
        try:
            val = int(d)
        except ValueError:
            val = float(d)
        finally:
            if val:
                converted_data.append(val)
    return converted_data

converted = int_float_converter(['-1','9','7.8'])
print(converted)
# [-1, 9, 7.8]
int(x) if int(x) == float(x) else float(x)

是确定字符串是整数还是浮点数的有用方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中,如何将列表列表中的字符串转换为其他类型,如整数,浮点数,布尔值等? - In Python how do you convert strings in a list of list to other types, such as ints, floats, booleans, etc? 如何遍历字符串列表并识别整数和浮点数,然后将它们添加到列表中? - How do I iterate over a list of strings and identify ints and floats and then add them to a list? python将列表中的字符串转换为int和float - python converting strings in list to ints and floats 我可以使用%f和%d将浮点数和整数格式化为列表中的字符串吗? - Can I use %f and %d to format floats and ints to strings in a list? 如何将字符串列表转换为字典中的整数列表? - How do I convert a list of strings to a list of ints inside a dictionary? 无法将浮点数转换为整数 - Unable to convert floats to ints 在 Pandas 中将浮点数转换为整数? - Convert floats to ints in Pandas? 在Python中,如何将int和字符串列表转换为Unicode? - In Python, how do I convert a list of ints and strings to Unicode? 如何从列表(txt 文件)中读取字符串并将它们打印为整数、字符串和浮点数? - How to get read strings from a list(a txt file) and print them out as ints, strings, and floats? 多嵌套列表中的整数和浮点数之和 - Sum of ints and floats in a multi nested list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM