python - 比较 Python 字典中的值

标签 python dictionary

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

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

抱歉,如果我没有足够清楚地表达问题是什么。

最佳答案

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

关于python - 比较 Python 字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749620/

相关文章:

python - IntelliJ IDEA - 如何将远程 PYTHONPATH 映射到本地环境?

Python 正则表达式 - r 前缀

python - 为什么从文件数据打印时出现错误,但从命令行打印时却没有

Python:将变量的值放入新字典中

iphone - Python--如何将变量的值写入iPhone(iOS 4)中的粘贴板/

python - 使用 beautifulsoup 从多个 URL 中抓取 3 个表

c++ - BGL adjacency_list<listS, listS>::vertex_descriptor 计算结果为 void*

Swift:如何正确地继续更新另一个字典中的字典?

python - 使用 python-mysql 连接到旧的 mysql 安装,

java - 如何将 "check"强制转换?