将值列表转换为字符串列表

时间:2016-02-10 03:49:51

标签: python python-2.7 python-2.x

我有一个如下所示的值列表:

l = [qeqw, qqweqw, qweqeqe ,qeewqewq]

如何将列表转换为字符串列表,如:

l = ['qeqw', 'qqweqw', 'qweqeqe' ,'qeewqewq']

3 个答案:

答案 0 :(得分:2)

试试这个:

[str(item) for item in l]

答案 1 :(得分:1)

如果您的列表包含变量,您可以使用此hack,但如果其他变量具有列表中变量的值,您也会在结果列表中包含它们:

l = [name for name in globals() if globals()[name] in l]

如果您的列表包含实际具有名称属性的对象,则可以使用此方法:

l = [e.__name__ for e in l]

如果您只想将值转换为str

l = [str(i) for i in l]

答案 2 :(得分:0)

首先,列表的构造将用您的值替换您在列表中使用的名称:

>>> a,b,c=1,2,'three'
>>> li=[a,b,c]
>>> li
[1, 2, 'three']

对于大多数对象,没有通用或可接受的方法将给定值与Python中的名称相关联。

有例外。许多可调用对象(函数,方法,模块,类但不是类实例)具有__name__属性:

>>> import os as noname_module
>>> noname_module.__name__
'os'
>>> def func(): pass
... 
>>> f=func
>>> f.__name__
'func'
>>> m=[].append
>>> m.__name__
'append'
>>> class O:
...    pass
... 
>>> O.__name__
'O'

但是,大多数Python对象具有__name__属性:

>>> a=1
>>> a.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__name__'
>>> s="string"
>>> s.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'
>>> f.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute '__name__'
>>> O().__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: O instance has no attribute '__name__'

str函数将生成对象的字符串表示形式:

>>> [(type(e), str(e)) for e in (a,s,f)] 
[(<type 'int'>, '1'), (<type 'str'>, 'string'), (<type 'float'>, '1.0')]

但是只有为该对象定义了str方法:

>>> o=O()
>>> str(o)
'<__main__.O instance at 0x10bcc23f8>'

有一个'hack'循环遍历locals()或globals()来尝试将名称与值相关联。但是,这有很多问题。

首先,例如:

>>> a=1
>>> b=1
>>> c=1
>>> d=1.0
>>> [n for n in globals() if globals()[n]==1]
['a', 'b', 'c', 'd']      # 1.0 and 1 are equal in Python's mind
>>> l=[a]
>>> [n for n in globals() if globals()[n] in l]
['a', 'b', 'c', 'd']      # ambiguous and incorrect... 

您可以将名称添加到您自己的对象中:

>>> o=O()
>>> o.__name__=O.__name__
>>> o.__name__
'O'

但这对大多数不可变的内置类型都不起作用。

所以只需接受它:没有明确的方法将值与Python中的明确名称相关联,除非它有__name__

那就是说,为了进一步“破解”你可以尝试:

def v2n(o):
    try:
        return "'{}'".format(o.__name__)
    except AttributeError:
        pass
    li=[n for n in globals() if globals()[n] is o and not n=='_']  
    if len(li)>1:
        return "Value of '{}' is ambiguous. Could be any of {}".format(str(o), ", ".join(["'{}'".format(e) for e in li]))
    elif len(li)==1:
        return "'{}'".format(li[0])
    else:
        return "No name"

试试看:

>>> a=1
>>> b=1
>>> c=1
>>> f1=1.0
>>> f2=1.0
>>> f3=2.0
>>> class O: pass
>>> def func(): pass
... 
>>> f=func
>>> print '\n'.join([v2n(_) for _ in (a,b,c,f1,f2,f3, O, O(), f)])  
Value of '1' is ambiguous. Could be any of 'a', 'c', 'b'
Value of '1' is ambiguous. Could be any of 'a', 'c', 'b'
Value of '1' is ambiguous. Could be any of 'a', 'c', 'b'
'f1'
'f2'
'f3'
'O'
No name
'func'

有点工作,但它被击中或错过。

如果你的算法依赖于获取对象的名称(除了可调用的,模块或类),你可能需要重新审视你是如何处理这个问题的。