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

2024-05-21 09:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子

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

请帮帮我。你知道吗


Tags: and代码in元素列表fordefrd
3条回答

可以使用while循环来调整子列表的长度,直到它通过附加所需的字符串与最长子列表的长度匹配为止。你知道吗

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

您只需浏览结果列表并检查元素的总数是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

您可以尝试以下方法:

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

相关问题 更多 >