python - 列出 csv 文件中的元素类型

标签 python list csv

我有一个简单的 csv 文件,我想用它来创建一个仅评估整数值的函数。下面是代码:

def type_setter(x):                                                                                                                           
    x = list(x)                                                                                                                               
    for i in x:                                                                                                                               
        for j in i :                                                                                                                          
            print type(j)                                                                                                                     
            if isinstance(j,int)==True:                                                                                                       
                eval(j)                                                                                                                   

    return x

问题是 j 值都被视为字符串变量,而不是整数和字符串的混合。有什么想法为什么会发生这种情况吗?

最佳答案

所有字段都是字符串。您不能使用 isinstance(j, int),因为它始终返回 False

使用str.isdigit相反:

>>> '1234'.isdigit()
True
>>> 'abcd'.isdigit()
False
>>> '-1234'.isdigit()
False
>>> '-1234'.lstrip('-').isdigit()
True

或者创建一个使用 try-except 和 int 的辅助函数:

def is_int(x):
    try:
        int(x)
    except ValueError:
        return False
    return True

示例:

>>> is_int('1234')
True
>>> is_int('xyz')
False
>>> is_int('-1')
True

关于python - 列出 csv 文件中的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809096/

相关文章:

Python GUI登录程序

python - python : how to loop list to find what elements of list begin with 的循环

javascript - 如何迭代 JSON 列表?

firebase - 如何在flutter中将数据从CSV文件导入数据库

python - 使用 shell 或批处理命令行将 Python Pretty 表转换为 CSV

python - python -m 标志的含义

python - Google AppEngine、Django 和 request.FILES

python - 根据他们的位置创建一个新列表

python - 如何循环Python列表以将其从M个值扩展到N个值(M < N)?

python - 在 txt 中查找分隔符以使用 Python 转换为 csv