python - 无法将每个子列表中包含 2 个元素的列表转换为单个字符串

标签 python python-3.x

所以,我需要将一个包含子列表的列表(每个子列表有 2 个元素)转换为一个字符串

我有什么:

[['A','B'],['C','D']]

我想转换成什么:

"ABCD"

我试过这个:

list=[['A','B'],['C','D']]

hello=""

for i in list:

     hello=hello+i

print (hello)

说我有一个 TypeError,我不明白为什么。

最佳答案

你有一个可迭代的列表,所以作为 pythonic 方式,使用 itertools.chain.from_iterable 来展平你的列表,然后使用 str.join() 方法连接字符:

In [12]: from itertools import chain

In [13]: lst = [['A','B'],['C','D']]

In [14]: ''.join(chain.from_iterable(lst))
Out[14]: 'ABCD'

这里是针对使用两个 join 的基准测试,它表明 itertools 方法快 2 倍:

In [19]: %timeit ''.join(chain.from_iterable(lst))
10000 loops, best of 3: 114 µs per loop

In [20]: %timeit ''.join(''.join(w) for w in lst)
1000 loops, best of 3: 250 µs per loop

关于python - 无法将每个子列表中包含 2 个元素的列表转换为单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40946813/

相关文章:

python-3.x - python中的 Pandas 数据操作

datetime - 如何创建基本时间戳或日期? (Python 3.4)

python - Cython 安装 GCC 错误

python - Pandas 匹配 2 列中最接近的日期时间值 - 类型整数/长错误

python - netCDF4.Dataset 到 xarray 数据集的简单转换

python - 处理 : 时遇到错误

python - 如何在 Python 中将 typing.Union 转换为其子类型之一?

linux - os.read 在 inotify 文件描述符 : reading 32 bytes works but 31 raises an exception 上

python - 当我提到某个人时,我是否可以通过discord.py 让我的机器人通过私信联系他们?

python - 如何在python中显示类似于msdos tree命令的树?