什么数据结构用于构建不同大小的字符串列表的串联?
例如,
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/