【问题标题】:how to merge two list without including the element common in both list in python如何合并两个列表而不包括python中两个列表中的共同元素
【发布时间】:2021-02-01 20:05:46
【问题描述】:

list1= ['ALEX', 'George', 'shyam']

list2= ['George','Ram', 'shyam']

output=['Alex', 'George','Shyam','Ram']

我试过了。

    list1=['ALEX', 'George', 'shyam']
    list2=['George','Ram', 'shyam']
    output=list1
    for j in list2:
        for i in list1:
            if str(j)!=str(i):
                output=output+[j]
    print(output)

但是,这是错误的。请帮助我知道如何处理上述问题!我是编程菜鸟。提前致谢。

【问题讨论】:

  • 最后的清单是应该保持原来的物品顺序还是无所谓?
  • 你得到什么输出?

标签: python list append


【解决方案1】:
list1=['ALEX', 'George', 'shyam']
list2=['George','Ram', 'shyam']
res = list1.copy()

for el in list2:
    if el not in res:
        res.append(el)

print(res)

【讨论】:

  • 这将起作用并保持原始项目的顺序,但需要额外复制。
【解决方案2】:

要合并两个列表,请使用:

list1 = ['ALEX', 'George', 'shyam']
list2 = ['George','Ram', 'shyam']
resultList= list(set(list1 ) | set(list2))
print(resultList)

输出: ['shyam', 'George', 'ALEX', 'Ram']

【讨论】:

  • 这可行,但它会丢失所有原始订单 - 当然,如果不需要的话。
【解决方案3】:

集合不能有重复项。因此,将列表转换为集合并返回列表可以消除所有重复项。因此,将您的列表相加并将较大的列表转换为一组:

list1= ['ALEX', 'George', 'shyam']
list2= ['George','Ram', 'shyam']
result = set(list1 + list2)
print(list(result))

#prints ['Ram', 'George', 'ALEX', 'shyam']

【讨论】:

    【解决方案4】:

    这将给出与问题中所述相同的顺序

    list1= ['ALEX', 'George', 'shyam']
    
    list2= ['George','Ram', 'shyam']
    
    #output=['Alex', 'George','Shyam','Ram']
    
    output=[x.capitalize() for x in list1] # Copy list but capitalize each string e.g. ALEX -> Alex
    for name in list2: # iterate through list2
        if name.capitalize() not in output: # if it is not already in output, append it
            output.append(name)
            
    print(output)
    
    

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多