Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中构建不同大小字符串列表的结构_Python_Arrays_List_Numpy - Fatal编程技术网

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

在python中构建不同大小字符串列表的结构,python,arrays,list,numpy,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”字符串填充,以

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

例如:

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']
                   ]

这里有一种使用列表理解的方法。它包括计算列表的最大长度作为初始步骤:

L = (a_list, b_list, c_list)
maxlen = max(map(len, L))

res = [i+['null']*(maxlen-len(i)) for i in L]

print(res)

[['h', 'i', 'null', 'null', 'null'],
 ['t', 'h', 'e', 'r', 'e'],
 ['fr', 'ie', 'nd', 'null', 'null']]
您可以使用:


我想那会管用的。我有一个问题:如果需要将一个新列表添加到该数组中(比如list_d)到已经构建的结构中。我该怎么做呢?我认为最简单的方法是重新制作数组:将
list\u d
添加到
zip\u-longest
中。另一种方法是用
null
字符串填充
list_d
,使其与最长的元素长度相同,然后使用
np.vstack
或类似的方法,但这似乎很复杂,事实上,这不会为您节省太多的性能。问题是,我必须在循环中连接正在运行的列表,因为这些列表存储在不同的文件中。所以我真的不能(a_列表,b_列表,c_列表,…zzz_列表)那样做,我将不得不一个接一个地附加它@您想要字符串“null”吗?还是想要空字符串?不要紧,一个随机字符串,它只是得到每个长度相同的列表!
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')
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')