我有一个列表字典,其中数字作为键,字符串列表作为值。例如,
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/