python - 如何在两个列表中形成匹配元素的列表(包括重复项)?

标签 python list set duplicates match

我有两个列表:

string1Elements = ['down', 'down', 'down', 'down']
string2Elements = ['down', 'down', 'right', 'down']

我想形成两个列表共有的元素列表,包括重复项。我想要的结果如下:

['down', 'down', 'down']
<小时/>

我想到的匹配的一种思考方式如下:

0:状态如下:

string1Elements = ['down', 'down', 'down', 'down']
string2Elements = ['down', 'down', 'right', 'down']

两个列表的大小相同,因此可以任意选择一个。如果列表大小不同,则会选择较短的列表。

1:获取string1Elements的第一个元素(所选列表)。 string2Elements 中是否存在该元素?如果是,请将其附加到匹配列表中,并从 string1Elementsstring2Elements删除它。

string1Elements = ['down', 'down', 'down']
string2Elements = ['down', 'right', 'down']
matches         = ['down']

2:获取string1Elements的第一个元素。 string2Elements 中是否存在该元素?如果是,请将其附加到匹配列表中,并将其从 string1Elementsstring2Elements 中删除。

string1Elements = ['down', 'down']
string2Elements = ['right', 'down']
matches         = ['down', 'down']

3:获取string1Elements的第一个元素。 string2Elements 中是否存在该元素?如果是,请将其附加到匹配列表中,并将其从 string1Elementsstring2Elements 中删除。

string1Elements = ['down']
string2Elements = ['right']
matches         = ['down', 'down', 'down']

4:获取string1Elements的第一个元素。 string2Elements 中是否存在该元素?如果是,请将其附加到匹配列表中,并将其从 string1Elementsstring2Elements 中删除。

string1Elements = ['down']
string2Elements = ['right']
matches         = ['down', 'down', 'down']

5:所有元素均已检查。

<小时/>

上面的过程只是为了解释我想如何处理重复的元素。我实际上不想更改列表 string1Elementsstring2Elements

由于重复的元素,我认为集合不能以明显的方式使用:

matches = list(set(string2Elements).intersection(string1Elements))

我尝试使用列表理解进行快速测试:

matches = [element for element in string1Elements if element in string2Elements]

这些方法都不够。我怎样才能按照我描述的方式实现匹配?

最佳答案

您可以系统地从一个列表中弹出并附加到结果列表(如果它们匹配)。因为您已从列表中弹出,所以它不会将 list1 中的一个元素与 list2 中的五个元素匹配,因为它会被弹出。示例函数:

def intersect(a, b):
    if len(b) < len(a):  # iff b is shorter than a
        a, b = b, a      # swap the lists.
    b = b[:]  # To prevent modifying the lists
    return [b.pop(b.index(i)) for i in a if i in b]

用法:

list1 = ['down', 'down', 'down', 'down']
list2 = ['down', 'down', 'right', 'down']
matches = intersect(list1, list2)
print(" ".join(matches))

# Prints:
down down down

这与OP解释如何在问题中完成完全一样,除了它只从较短的列表中删除元素。
一个适用于多个列表的方法可以如下实现

def multi_intersect(*args):
    if len(args) == 1:
        try:
            return multi_intersect(*args)
        except TypeError:
            pass
    inters = [item for sublist in args for item in sublist]
    for arg in args:
        inters = intersect(inters, arg)
    return inters

关于python - 如何在两个列表中形成匹配元素的列表(包括重复项)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608546/

相关文章:

python - DRF- Django Rest Framework re_path 查询参数 - "Method\"GET\"not allowed."

python - DataFrame 列中的混合类型元素

python - 创建一个序列,每个元素中有两个满足一定的距离标准

list - grails 2.5-如何在config.groovy中放置列表

c++ - STL set::find 重新定义搜索

java - 在 HashSet 中搜索时如何使用正则表达式

python - SQLAlchemy Date Time 对象可以在 Flask 中显示本地时区吗

python - 从元组到 Pandas 中的多列

java - 在java中创建唯一值的列表

C++ std::set 插入时读取无效