python - 如何在Python中将ndarray数组列表转换为列表

标签 python list numpy

我有一个包含 10 个一维 ndarray 的列表,其中每个都包含一个字符串,并且我想要一个长列表,其中每个项目都是一个字符串(不再使用 ndarray)。我该如何实现?

最佳答案

我认为你需要先转换为数组,然后按 ravel 展平最后转换为列表:

a = [np.array([x]) for x in list('abcdefghij')]
print (a)
[array(['a'],
      dtype='<U1'), array(['b'],
      dtype='<U1'), array(['c'],
      dtype='<U1'), array(['d'],
      dtype='<U1'), array(['e'],
      dtype='<U1'), array(['f'],
      dtype='<U1'), array(['g'],
      dtype='<U1'), array(['h'],
      dtype='<U1'), array(['i'],
      dtype='<U1'), array(['j'],
      dtype='<U1')]

b = np.array(a).ravel().tolist()
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

另一个扁平化解决方案 chain.from_iterable :

from  itertools import chain

b = list(chain.from_iterable(a))
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

关于python - 如何在Python中将ndarray数组列表转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661124/

相关文章:

python - 运行 setup.py 时更改包名称

python - 如何使用 OpenCV 获取视频的时长

python - 按位或 "|"与 Python 中两个正幂的加法 "+"

python - 将列表拆分为单独但重叠的 block

python - 用python字符串的ascii序数列表

python - Python3 安装中缺少 Numpy 模块

Python 的数学计算很奇怪,为什么会这样?

python - numba 中零维数组的签名是什么

python - Pandas Series.value_counts() 的奇怪行为

c - 如何在 C 中将客户端的 IP 存储在数组中(套接字编程)