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

时间:2018-07-03 13:37:45

标签: 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']
                   ]

2 个答案:

答案 0 :(得分:4)

您可以使用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')

答案 1 :(得分:2)

这是使用列表理解的一种方法。首先需要计算列表的最大长度:

<?php 
// No direct access
defined('_JEXEC') or die; 
JHtml::_('behavior.formvalidator');
?>
<script>
jQuery(document).ready(function(){
    document.formvalidator.setHandler('passverify', function (value) {
        return (jQuery('input[type=password]').value == value); 
    });
});
</script>

<form class="form-validate" method="post" name="shout" onSubmit="submitbutton">

    <label>Navn</label><input class="inputbox required" name="LicensForm[name]" type="text" /><br/>
    <label>Bruger navn</label><input class="inputbox required validate-username" name="LicensForm[username]" type="text" /><br/>
    <label>Password</label><input id="password" class="inputbox required validate-password" name="LicensForm[password]" type="password" /><br/>
    <label>Bekræft password</label><input id="password2" class="inputbox required validate-passverify" name="LicensForm[password2]" type="password" /><br/>
    <label>Email</label><input class="inputbox required validate-email" name="LicensForm[email]" type="text" /><br/>

    <label>Indløs licensnøgle</label><input class="inputbox required" name="LicensForm[licens]" type="text" /><br/>

    <input class="validate" type="submit" name="submit" value="check licensnøgle"/>
</form>