繁体   English   中英

比较列表的Python字典中的值

[英]Comparing values in a Python dict of lists

我有一个列表的字典,数字作为键,字符串列表作为值。 例如,

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']
}

对不起,如果我没有表达出明显的问题。

在你的dict中创建一组所有名称。
然后,您可以创建一个允许您构造新dict的查找表。
这使用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']}

这是一个列表字典的事实是无关紧要的。 有些字符串必须根据其他字符串进行修改。

这些是字符串:

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()}

暂无
暂无

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

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