检查两个列表不共享的元素 [PYTHON 2.7]

Check for Elements Not Shared by Two List [PYTHON 2.7]

我有两个数组需要比较以删除某些元素。我的问题是比较数组元素以确保它们相同很容易,但是如何确保两个元素不相同?

for e in is_And_Should_Be: #delete who shouldn't be here
    for l in USERS:
        if (is_And_Should_Be[e] == USERS[l]):
            current = USERS[l]
            proc = Popen(['deluser', current],stdin=PIPE,stdout=PIPE,stderr=PIPE)
            if proc.returncode == 0:
                print "%s deleted" % current

如果我有 steve、dan 和 john 应该在那里,而 dan、steve 和 satan 已经在那里,我将如何确保只删除 satan,因为我的解决方案(或更确切地说是困境)会删了。提前致谢。

您可以执行以下操作(假设这是您提到的 USERS 的示例列表:

USERS = ["Steve", "Dan", "John", "Dan", "Steve", "Satan"]
while "Satan" in USERS:
    USERS.remove("Satan")
print USERS
['Steve', 'Dan', 'John', 'Dan', 'Steve']

master_list = ["Steve", "Dan", "John", "Satan"]

desired_list = ["Steve", "Dan", "John"]

unwanted_user = [name for name in master_list if not name in desired_list]

print(unwanted_user)

['Satan']

master_list.remove(unwanted_user[0])

print(master_list)

['Steve', 'Dan', 'John']

我的建议是使用 Python 的 sets 并找出不同之处:

is_and_should_be = ['Steve', 'Dan', 'John']
users = ['Steve', 'Dan', 'Satan']
deletables = set(users).difference(set(is_and_should_be))
for user_to_delete in deletables:
    users.remove(user_to_delete)

在上面,我假设您使用的是 Python lists, instead of arrays