加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:05:57 所属栏目:Python 来源:网络整理
导读:使用什么数据结构来构建不同大小的字符串列表的串联? 例如., a_list = ['h','i']b_list = ['t','h','e','r','e']c_list = ['fr','ie','nd'] 理想结构: my_structure = [ ['h','i'],['t','e'],['fr','nd'] ] 然后用’null’字符串填充它以在每个列表中获得
使用什么数据结构来构建不同大小的字符串列表的串联?

例如.,

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

理想结构:

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

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

my_structure = [    ['h','i','null','null'],'nd','null']
                   ]

解决方法

你可以使用 itertools.zip_longest

import itertools

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

array([['h','null']],dtype='<U4')

编辑:根据您的注释,您希望向阵列添加新列表,创建要使用的列表列表可能更简单,并且您可以动态地追加到该列表:

a_list = ['h','nd']

my_list = [a_list,c_list]

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

>>> my_arr
array([['h',dtype='<U4')

然后,您可以向my_list添加新列表:

d_list = ['x']

my_list.append(d_list)

my_arr = np.array(list(itertools.zip_longest(*my_list,['x',dtype='<U4')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读