比较Python字典列表中的值

3

我有一个字典,其中数字为键,字符串列表为值。例如:

my_dict = {
    1: ['bush', 'barck obama', 'general motors corporation'],
    2: ['george bush', 'obama'],
    3: ['general motors', 'george w. bush']
}

我希望的是对每个键的每个列表中的每个项目进行比较,如果该项目是另一个项目的子字符串,则将其更改为更长的字符串。所以,这有点像非常肮脏的共指消解。我真的无法理解如何做到这一点。下面是我想法的伪代码:
for key, value in dict:
    for item in value:
        if item is substring of other item in any other key, value:
            item = other item

因此,最终我的字典将会像这样:

my_dict = {
    1: ['george w. bush', 'barck obama', 'general motors corporation'],
    2: ['george w. bush', 'barck obama'],
    3: ['general motors corporation', 'george w. bush']
}

如果我没有清楚地表达问题,对此感到抱歉。


“george bush” 不是 “george w. bush” 的子字符串,所以如果您想要预期的输出,您需要更高级的匹配。顺便说一下,奥巴马的名字是巴拉克。 - AChampion
是的,谢谢,那是我复制/粘贴到各处的一个打字错误。关于“'george bush'”不是“'george w. bush'”的子字符串这一事实 - zvone的代码似乎已经处理了这个问题。 - Zlo
它确实可以,但是@zvone(和我的)代码可能会失败更一般的情况,例如 g. w. bush 不会变成 george w. bush - AChampion
2个回答

6
创建一个包含字典中所有名称的集合。
然后,您可以创建一个查找表,以便构建一个新的字典。
使用max()中的key=len来选择具有子字符串的最长名称:
>>> s = {n for v in my_dict.values() for n in v}
>>> lookup = {n: max((a for a in s if n in a), key=len) for n in s}
>>> {k: [lookup[n] for n in v] for k, v in my_dict.items()}
{1: ['george w. bush', 'barck obama', 'general motors corporation'],
 2: ['george bush', 'barck obama'],
 3: ['general motors corporation', 'george w. bush']}

或者你可以直接原地使用max()函数:

>>> s = {n for v in my_dict.values() for n in v}
>>> {k: [max((a for a in s if n in a), key=len) for n in v] for k, v in my_dict.items()}
{1: ['george w. bush', 'barck obama', 'general motors corporation'],
 2: ['george bush', 'barck obama'],
 3: ['general motors corporation', 'george w. bush']}

为了获得所需的输出,您需要比仅仅使用子字符串更加严格的匹配标准:
>>> s = {n for v in my_dict.values() for n in v}
>>> {k: [max((a for a in s if all(w in a for w in n.split())), key=len) for n in v] for k, v in my_dict.items()}
{1: ['george w. bush', 'barck obama', 'general motors corporation'],
 2: ['george w. bush', 'barck obama'],
 3: ['general motors corporation', 'george w. bush']}

太好了,谢谢!我应该学习更多关于列表/字典推导式的知识,因为现在这些代码行对我来说看起来非常神秘。 - Zlo

1
这是一个列表字典并不重要,有些字符串需要根据其他字符串进行修改。 以下是需要修改的字符串:
all_strings = [s for string_list in my_dict.values() for s in string_list]

替换字符串:
def expand_string(s, all_strings):
    # compare words
    matches = [s2 for s2 in all_strings
               if all(word in s2.split() for word in s.split())]
    if matches:
        # find longest result
        return sorted(matches, key=len, reverse=True)[0]
    else:
        # this wont't really happen, but anyway
        return s

替换所有内容:

result = {k: [expand_string(s, all_strings) for s in v]
          for k, v in my_dict.items()}

FYI: max(matches, key=len) 相当于 sorted(matches, key=len, reverse=True)[0] - 但不需要构建新列表的开销。 - AChampion
@AChampion 没错,谢谢。我从来不知道 max 还有 key :) - zvone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接