简体   繁体   English

比较两个列表以返回一个列表,其中所有元素都为0,除了那些在保持索引时匹配的列表?

[英]Compare two lists to return a list with all elements as 0 except the ones which matched while keeping index?

I am a bit stuck on this: 我有点困惑于此:

a = [1,2,3,2,4,5]
b = [2,5]

I want to compare the two lists and generate a list with the same items as a , but with any items that don't occur in b set to 0. Valid outputs would be these: 我想比较两个列表并生成一个列表,其中包含与a相同的项目,但是b没有出现的任何项目设置为0.有效输出将是:

c = [0,2,0,0,0,5]
# or
c = [0,0,0,2,0,5]

I would not know the number elements in either list beforehand. 我事先不知道任何一个列表中的数字元素。

I tried for loops but 我试图for循环,但

['0' for x in a if x not in b]

It removes all instances of 2. Which I only want to remove once(it occurs once in b for the moment). 它删除了所有2的实例。我只想删除一次(它暂时在b出现一次)。 I need to add a condition in the above loop to keep elements which match. 我需要在上面的loop添加一个条件来保持匹配的元素。

The following would work: 以下将有效:

a = [1,2,3,2,4,5]
b = [2, 5]

output = []

for x in a:
    if x in b:
        b.remove(x)
        output.append(x)
    else:
        output.append(0)

or for a one-liner, using the fact that b.remove(x) returns None : 或者对于单行,使用b.remove(x)返回None的事实:

a = [1,2,3,2,4,5]
b = {2, 5}

output = [(b.remove(x) or x) if x in b else 0 for x in a]

If the elements in b are unique, this is best done with a set , because sets allow very efficient membership testing: 如果b中的元素是唯一的,那么最好使用set来完成,因为集合允许非常有效的成员资格测试:

a = [1,2,3,2,4,5]
b = {2, 5}  # make this a set

result = []
for num in a:
    # If this number occurs in b, remove it from b.
    # Otherwise, append a 0.
    if num in b:
        b.remove(num)
        result.append(num)
    else:
        result.append(0)

# result: [0, 2, 0, 0, 0, 5]

If b can contain duplicates, you can replace the set with a Counter , which represents a multiset: 如果b可以包含重复项,则可以使用Counter替换该集合,该Counter代表多重集:

import collections

a = [1,2,3,2,4,5]
b = collections.Counter([2, 2, 5])

result = []
for num in a:
    if b[num] > 0:
        b[num] -= 1
        result.append(num)
    else:
        result.append(0)

# result: [0, 2, 0, 2, 0, 5]

Here's one way using set . 这是使用set的一种方式。 Downside is the list copy operation and initial set conversion. 下行是list复制操作和初始set转换。 Upside is O(1) removal and lookup operations. 上行是O(1)删除和查找操作。

a = [1,2,3,2,4,5]
b = [2,5]

b_set = set(b)
c = a.copy()

for i in range(len(c)):
    if c[i] in b_set:
        b_set.remove(c[i])
    else:
        c[i] = 0

print(c)

[0, 2, 0, 0, 0, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM