如何将混合类型列表转换为字符串

4

我有一个混合类型列表:

A=[0, '0,1', 0, '0,1', '0,1', '0,1', '0,1', 0]

想要把所有元素都转换成字符串,但是我尝试了以下代码:

for i in A:
  if type(i) == int:
    str(i)
  print(type(i))

并且不对这些类型进行任何更改

<class 'int'>
<class 'str'>
<class 'int'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>

2
为什么不使用列表推导式:A = [str(x) for x in A] - Rocky Li
2个回答

1

您需要覆盖第三行中的类型,str(i) 应该改为 i = str(i)

A=[0, '0,1', 0, '0,1', '0,1', '0,1', '0,1', 0]

for i in A:
  if type(i) == int:
    i = str(i)
  print(type(i))


# output
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

请注意,这不会改变原始列表的类型。如果要更改类型,您需要在列表本身中覆盖该值。
for i in range(len(A)):
  if type(A[i]) == int:
    A[i] = str(A[i])

1

chr 是一个返回新的单个字符 str 的函数;如果你不分配结果,它就是一个无操作。因此,最简单的修复方法是:

for i, x in enumerate(A):  # enumerate to get indices so we can assign back
    if type(x) is int:     # Type checks use is, not == (or use isinstance)
        A[i] = x = chr(x)  # Reassign x as well if you want to use the new value
    print(type(x))

话虽如此,它不会生成字符串'0',而是会生成字符串'\x00',因为chr基于原始Unicode序数进行转换(在Py2上基于ASCII序数)。如果您想要生成'0',请改用str

for i, x in enumerate(A):  # enumerate to get indices so we can assign back
    if type(x) is int:
        A[i] = x = str(x)
    print(type(x))

只是一个更新,楼主修改了问题,把 chr 改成了 str - Sufiyan Ghori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接