合并两个没有重复值的列表

问题描述 投票:0回答:7
list1 = ["palani", "samy","be"]
list2 = ["palani", "samys","be"]

def find_common(list1,list2):
    for x in list1:
      for y in list2:
        if x == y :
          list2.remove(x) 


    print" unique string 1:",list1
    print" unique string 2:",list2
    print" combained string 2:",list1.append(list2)


find_common(list1,list2)

为什么我会得到

None

python python-2.7
7个回答
12
投票

这可以通过使用 set 来完成:

a = ['hello', 'world']
b = ['hello', 'universe']

unique = list(set(a + b))

print(unique)

# ['universe', 'hello', 'world']

注意:这不适用于字典列表!


8
投票
import numpy as np

np.unique(list1+list2) # keeps only non dublicates

这也可以保持顺序,以防万一这是优先事项


2
投票

list.append
方法就地修改列表并返回
None
。您应该使用
+
运算符来合并两个列表。

改变:

print" combained string 2:",list1.append(list2)

至:

print" combained string 2:",list1+list2

2
投票
list3 = list1[:]
[list3.append(i) for i in list2 if i not in list1] 

print(l3)
['palani', 'samy', 'be', 'samys']

1
投票

你可以尝试:

def find_common(list1,list2):
    return list(set(list1+list2))

0
投票

您可以使用

set
操作来实现此目的。

unique = list(set(list1).symmetric_difference(set(list2)))

0
投票

总的来说,使用

set
是正确的选择。这是其他一些答案的变体,但允许不止两个列表。

def merge_lists(*args) -> list:
    """Merge two or more sequences together"""
    return list(set(args[0]).union(*args[1:]))

示例:

a = [6, 8, 10]
b = [2, 4, 6]
c = [4, 8, 12]
merge_lists(c, b, a)
# Output: [2, 4, 6, 8, 10, 12]
merge_lists(c)
# Output: [8, 4, 12]
© www.soinside.com 2019 - 2024. All rights reserved.