加入2个列表时添加空字符串-Python

时间:2019-03-21 12:03:02

标签: python python-2.7 list

我有2个列表

mainlist=[['RD-12',12,'a'],['RD-13',45,'c'],['RD-15',50,'e']] and 
sublist=[['RD-12',67],['RD-15',65]]

如果我通过使用以下代码基于第一要素条件同时加入两个列表

def combinelist(mainlist,sublist):
   dict1 = { e[0]:e[1:] for e in mainlist }
   for e in sublist:
      try:
         dict1[e[0]].extend(e[1:])
      except:
         pass
   result = [ [k] + v for k, v in dict1.items() ]
   return result

其结果如下所示

[['RD-12',12,'a',67],['RD-13',45,'c',],['RD-15',50,'e',65]]

因为它们不是子列表中“ RD-13”的元素,所以我想在此空字符串。

最终输出应为

[['RD-12',12,'a',67],['RD-13',45,'c'," "],['RD-15',50,'e',65]]

请帮助我。

4 个答案:

答案 0 :(得分:1)

您可以只浏览结果列表,然后检查元素总数为2而不是3。

for list in lists:
    if len(list) == 2:
        list.append(" ")

更新:

如果子列表中还有更多项目,只需减去包含列表中“键”的列表,然后添加所需的字符串即可。

def combinelist(mainlist,sublist):
   dict1 = { e[0]:e[1:] for e in mainlist }
   list2 = [e[0] for e in sublist]
   for e in sublist:
      try:
         dict1[e[0]].extend(e[1:])
      except:
         pass
   for e in dict1.keys() - list2:
       dict1[e].append(" ")
   result = [[k] + v for k, v in dict1.items()]
   return result

答案 1 :(得分:1)

您可以使用while循环来解决您的问题,方法是通过添加所需的字符串来调整子列表的长度,直到与最长子列表的长度匹配为止。

for list in result:
    while len(list) < max(len(l) for l in result):
        list.append(" ")

答案 2 :(得分:0)

您可以尝试以下操作:

mainlist=[['RD-12',12],['RD-13',45],['RD-15',50]]
sublist=[['RD-12',67],['RD-15',65]]
empty_val = ''

# Lists to dictionaries
maindict = dict(mainlist)
subdict = dict(sublist)
result = []
# go through all keys
for k in list(set(list(maindict.keys()) + list(subdict.keys()))):
    # pick the value from each key or a default alternative
    result.append([k, maindict.pop(k, empty_val), subdict.pop(k, empty_val)])
# sort by the key
result = sorted(result, key=lambda x: x[0])

您可以根据需要设置空值。

更新

遵循新条件,将如下所示:

mainlist=[['RD-12',12,'a'], ['RD-13',45,'c'], ['RD-15',50,'e']]
sublist=[['RD-12',67], ['RD-15',65]]

maindict = {a:[b, c] for a, b, c in mainlist}
subdict = dict(sublist)
result = []

for k in list(set(list(maindict.keys()) + list(subdict.keys()))):
    result.append([k, ])
    result[-1].extend(maindict.pop(k, ' '))
    result[-1].append(subdict.pop(k, ' '))

sorted(result, key=lambda x: x[0])

答案 3 :(得分:0)

另一种选择是将子列表转换为字典,以便可以轻松快速地访问项目。

    </html>
        <!DOCTYPE html>
        <head></head>
        <body>

            <form action="ingupdate.php" method="POST" >
                <input type="text" name="noie" placeholder="Enter the no of ingredients to add" style="width:200px;" id="noie"> 
                <button id="noieb">Enter</button>`

                <div id='my-dialog-id' title='my dialog title'>
                    <p>The item <?php print_r($coderepeat);?> already exists do u wish to update??</p>
                    <button name="ingyes" >YES</button>
                    <button name="ingno">NO</button>
                </div>

            <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

        </body>

您可以这样做(它修改了sublist_dict = dict(sublist) ):

mainlist

或一个班轮名单理解(它会产生一个新名单):

for i, e in enumerate(mainlist):
  data: mainlist[i].append(sublist_dict.get(e[0], ""))
#=> [['RD-12', 12, 'a', 67], ['RD-13', 45, 'c', ''], ['RD-15', 50, 'e', 65]]


如果要跳过缺少的元素:

[ e + [sublist_dict.get(e[0], "")] for e in mainlist ]