python - 在python中构建具有不同大小的字符串列表的结构

标签 python arrays list numpy

什么数据结构用于构建不同大小的字符串列表的串联?

例如,

a_list = ['h','i']
b_list = ['t','h','e','r','e']
c_list = ['fr', 'ie','nd']

所需的结构:

my_structure = [ ['h','i'],
                 ['t','h','e','r','e'],
                 ['fr', 'ie','nd']
               ]

然后用'null'字符串填充它以在每个列表中获得相同的大小:

 my_structure = [    ['h','i','null','null','null'],
                     ['t','h','e','r','e'],
                     ['fr', 'ie','nd','null', 'null']
                   ]

最佳答案

你可以使用 itertools.zip_longest :

import itertools

np.array(list(itertools.zip_longest(a_list, b_list, c_list, fillvalue='null'))).T

array([['h', 'i', 'null', 'null', 'null'],
      ['t', 'h', 'e', 'r', 'e'],
      ['fr', 'ie', 'nd', 'null', 'null']],
  dtype='<U4')

编辑:根据您要向数组添加新列表的评论,创建您要使用的列表的列表可能更直接,您可以附加到该列表有点动态地列出:

a_list = ['h','i']
b_list = ['t','h','e','r','e']
c_list = ['fr', 'ie','nd']

my_list = [a_list, b_list, c_list]

my_arr = np.array(list(itertools.zip_longest(*my_list, fillvalue='null'))).T

>>> my_arr
array([['h', 'i', 'null', 'null', 'null'],
       ['t', 'h', 'e', 'r', 'e'],
       ['fr', 'ie', 'nd', 'null', 'null']],
      dtype='<U4')

然后你可以添加一个新列表到my_list:

d_list = ['x']

my_list.append(d_list)

my_arr = np.array(list(itertools.zip_longest(*my_list, fillvalue='null'))).T

>>> my_arr
array([['h', 'i', 'null', 'null', 'null'],
       ['t', 'h', 'e', 'r', 'e'],
       ['fr', 'ie', 'nd', 'null', 'null'],
       ['x', 'null', 'null', 'null', 'null']],
      dtype='<U4')

关于python - 在python中构建具有不同大小的字符串列表的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156042/

相关文章:

Python SQLite3 : want to iteratively fetching rows, 但代码正在拉取每隔一行

php - 在 PHP 中应该使用数组还是类来保存多个变量?

javascript - 如何在 App 脚本中比较 2 个数组

JavaScript:带有函数数组的TypeError

列表字典中项目的 Python 计数

css - 使用 CSS 实现无序列表中的文本缩进

python - 如何在Python中根据另一个集合对一个集合进行排序?

python - 使用对象的 id() 作为哈希值

sharepoint - 共享点列表中带有C#语法突出显示的自定义文本字段

python - 计算均方,绝对偏差和自定义相似性度量-Python/NumPy