search

Home  >  Q&A  >  body text

python列表内的类型转换

大家好,我尝试用下面的方法在一个存储了unciode类型数字的列表内直接做int转换,代码和错误信息如下:

pass_list = [int(item) for item in data_list]

    Traceback (most recent call last):
  File "C:/Projects/pycharm/query_mongo/query_mongo.py", line 183, in <module>
    verify_pass_id_in_plane(collect_name1, collect_name2)
  File "C:/Projects/pycharm/query_mongo/query_mongo.py", line 123, in verify_pass_id_in_plane
    pass_list = [int(item) for item in data_list]
ValueError: invalid literal for int() with base 10: ''

data_list里保存的数据类似这样, [u'149, u'150'], 我想得到一个[149,150]这样的list, 用pycharm里用调试的时候没有问题,直接运行就报上面的错误,请问要如何解决?谢谢

大家讲道理大家讲道理2786 days ago467

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-18 10:30:18

    Reporting this error means that your data_list contains a value that cannot be converted into int, such as an empty string or None. Check the value of data_list carefully

    reply
    0
  • PHPz

    PHPz2017-04-18 10:30:18

    It is best to check the int() object type, for example through the isnumeric() method of string:

    pass_list = [int(item) for item in data_list if item.isnumeric()]

    reply
    0
  • Cancelreply