加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

比较列表的Python字典中的值

发布时间:2020-12-20 11:58:27 所属栏目:Python 来源:网络整理
导读:我有一个列表的字典,数字作为键,字符串列表作为值.例如., my_dict = { 1: ['bush','barck obama','general motors corporation'],2: ['george bush','obama'],3: ['general motors','george w. bush']} 我想要的是比较每个列表中的每个项目(对于每个键),如果
我有一个列表的字典,数字作为键,字符串列表作为值.例如.,

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读