【问题标题】:Conditional Merging of Lists列表的条件合并
【发布时间】:2018-12-25 09:39:44
【问题描述】:

我正在尝试根据以下规则合并两个列表:

list1 中的第一个元素应与 list2 中的最后一个元素合并,list1 中的第二个元素应与 list2 中的倒数第二个元素合并,以此类推。

如果 list1/list2 中的元素为 None,则另一个列表中的对应元素应保持在合并列表中的状态。

我觉得我可能必须在这里使用链接列表,但我不确定。我试图通过遍历列表来找出解决方案,但我无法弄清楚这里的逻辑。

def merge_list(list1, list2):
    merged_data=""
    new_str=""
    #write your logic here
    for l1 in list1:
        for l2 in list2[::-1]:
            if l1 is None or l2 is None:
                pass
            else:
                new_str = l1+l2
                i=list2.index(l2)
                print(new_str)
            break
    #return resultant_data


list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)

预期输出:

“一天一苹果,医生远离我”

【问题讨论】:

  • 我应该假设两个字符串的长度相同吗?

标签: python list


【解决方案1】:

您可以使用zip 同时遍历两个列表:

def merge_list(lst1,lst2):
    s = ''
    for x, y in zip(lst1, lst2[::-1]):
        if y and x:
            s += x + y
        elif x:
            s += x
        elif y:
            s += y
        s += ' '
    return s[:-1]

list1 = ['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2 = ['y','tor','e','eps','ay',None,'le','n']
merged_data = merge_list(list1,list2)

print(merged_data)
# An apple a day keeps the doctor away

您可以缩短它并使用列表理解,如下所示(但是,我更喜欢另一个更易读的):

def merge_list(lst1,lst2):
    return ' '.join(x + y if x and y else x if x else y for x, y in zip(lst1, lst2[::-1]))

【讨论】:

  • 建议:s += ''.join([x, y]) -> s += x + ys += f"{x}{y}"
  • @juanpa.arrivillaga,似乎是避免不必要的join() 的更好方法。谢谢。
【解决方案2】:

假设两个列表的长度相同

>>> list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
>>> list2=['y','tor','e','eps','ay',None,'le','n']
>>> ' '.join([l1 + l2 if l1 and l2 else l1 if l1 and not l2 else l2 for l1, l2 in zip(list1, reversed(list2)) if l1 and l2])
'An apple a day keeps the doctor away'

【讨论】:

    【解决方案3】:

    确保列表长度相同,然后只需一个 zip 就足够了。但是用''(空字符串)替换None

    ["".join(row) for row in zip(list1, reversed(list2))]
    

    =>

    ['An', 'apple', 'a', 'day', 'keeps', 'the', 'doctor', 'away']
    

    【讨论】:

      【解决方案4】:

      首先使用list comprehensions合并两个列表,然后将该列表转换为string

      " ".join(str(x) for x in [list1[i]+list2[len(list2)-1-i] if list2[len(list2)-1-i] != None else list1[i] for i in range(len(list1))])
          'An apple a day keeps the doctor away'
      

      【讨论】:

        【解决方案5】:
        def fetch_index(list2, item_index):
            x = list2[::-1]
            return x[item_index]
        
        def merge_list(list1, list2):
            list_3 = []
            #write your logic here
            for l1 in list1:
                l2 = fetch_index(list2, list1.index(l1))
                if l1 is None and l2 is None:
                    pass
                elif l1 is None:
                    list_3.append(l2)
                elif l2 is None:
                    list_3.append(l1)
                else:
                    list_3.append(l1+l2)
            return(list_3)
        
        list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
        list2=['y','tor','e','eps','ay',None,'le','n']
        x = merge_list(list1,list2)
        print ' '.join(i for i in x)
        

        如果您不想使用 zip,请使用更长的版本

        【讨论】:

          【解决方案6】:

          不使用 zip 的简短回答。

          " ".join([list1[x]+[y if y is not None else '' for y in list2 ][::-1][x] for x in range(len(list1)-1)]
          

          【讨论】:

            【解决方案7】:
            list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
            list2=['y','tor','e','eps','ay',None,'le','n']
            a=list2.remove(None)
            list2.insert(5,"")
            list3 = [ str(x[0]) + x[1]   for x in zip(list1, list2[::-1]) ]
            print ' '.join(list3)
            

            输出:

            一天一苹果,医生远离我

            【讨论】:

            • 欢迎来到 SO。通过添加对代码如何回答问题的说明来改进纯代码答案。
            【解决方案8】:
            l1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
            l2=['y','tor','e','eps','ay',None,'le','n']
            a=l2[::-1]
            l3=[]
            for i in range(len(l1)):
                if(l1[i] is None or a[i] is None):
                    l3.append(l1[i])`enter code here`
                else:
                    l3.append(l1[i]+a[i])
            
            
            print(" ".join(l3))
            

            【讨论】:

            • 嗨,欢迎来到 SO!尽量不要只提供代码答案。如果您觉得您的答案比其他答案做得更好,您也可以详细说明:)
            【解决方案9】:
            def merge_list(list1, list2):
            merged_data = ""
            list3 = list1   
            for i in range(1, 2*len(list2) + 1,2):    #Converting both lists in single list
                list3.insert(i, list2[-1])    # Adding last elements of list2 at alternate to positions elements of list3
                list2.pop()  #Removing the last element from list2
            list3 = ["" if i is None else i for i in list3]   # Handling NoneType condition. If there is "None", convertted to ""
            for i in range(0,len(list3),2):
                word="".join(list3[i:i+2])   #joining the elements in set of two
                merged_data=merged_data+word+" "   #converting above word into one
            return merged_data
            

            【讨论】:

            • 很抱歉给您带来不便。给我一些时间来改变并重新发布它
            • 我希望这能给你正确的见解
            • 是的!够了。
            【解决方案10】:
            list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
            list2=['y','tor','e','eps','ay',None,'le','n']
            s=''
            new=''
            for i in list1:
                for j in list2[::-1]:
                    if i==None:
                        i=''
                    elif j==None:
                        j=''
                    new=i+j
                    s=s+new+' '
                    list2.pop(-1)
                    break
            print(s)
            

            【讨论】:

            • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
            猜你喜欢
            • 1970-01-01
            • 2012-09-07
            • 2014-03-07
            • 1970-01-01
            • 2016-02-08
            • 1970-01-01
            • 2014-01-26
            • 2018-10-08
            • 2015-01-09
            相关资源
            最近更新 更多