Python:当尝试将int转换为list时,int对象不可迭代

时间:2017-09-19 11:06:35

标签: python

尝试检查value是否为list,然后将此列表转换为逗号分隔字符串,否则请按原样使用value

def one():
    val = 1
    v = (val, ','.join(map(str, val)))[isinstance(val, list)]

if __name__ == '__main__':
    one()

但有错误:'int' object is not iterable

如果val=[1,2]v=1,2

3 个答案:

答案 0 :(得分:2)

Python并不是懒惰的(因此),因此无论访问什么值,都会执行连接。为什么不

if isinstance(val, list):
    val = ",".join(map(str, val))

答案 1 :(得分:2)

问题是地图有这个签名地图(功能,可迭代,......)

意味着第二个参数必须是可迭代类型 - > int不可迭代,这就是你得到错误的原因。

答案 2 :(得分:0)

根据您的要求,您可以创建如下功能:

def get_value(x):
    return ','.join(map(str, x)) if isinstance(x, list) else x
    #                ^ To type-cast each element of list to a string

示例运行:

>>> get_value(123)
123
>>> get_value([1, 2, 3])
'1,2,3'

但是我建议使用collections.Iterable检查对象类型,它将为所有迭代器(如list,tuple,string等)返回True,而不仅仅是list。因此你的功能应该是:

from collections import Iterable

def get_value(x):
    return ','.join(map(str, x)) if isinstance(x, Iterable) else x