【问题标题】:PYTHON: concating values if similar values found in a dictonaryPYTHON:连接在字典中找到的相似值的值
【发布时间】:2019-09-20 20:12:57
【问题描述】:

蟒蛇: 我有一个字典:

abc = {[
    ["buy", "contract_type"], ["apple", "product"], ["from", "o"],
    ["Alex", "trader_name"], ["heeb", "trader_name"], ["of", "o"],
    ["APPLE", "counter_party"], ["INC", "counter_party"]]}

我想要的是, 基本上连接字典中相似键的值

new_abc = {[
    ["buy", "contract_type"], ["apple", "product"], ["from", "o"],
    ["Alex heeb", "trader_name"], ["of", "o"],
    ["APPLE INC", "counter_party"]]}

【问题讨论】:

  • 那是列表,不是字典,你试过什么?
  • 我认为您想通过关联的第二个元素对第一个元素进行分组,然后连接找到的第一个元素并将它们与第二个元素重新关联。
  • @Alfe - 这无法解释为什么 fromof 保持分开
  • @Sayse 没错。这就是为什么我要求澄清。我想不结合这些只是纸上计算结果时的一个错误。
  • 你的编辑只是把它变成了一个集合而不是一个列表。

标签: python list concatenation


【解决方案1】:

试试这个:

d = {}
for a, b in abc:
    d.setdefault(b, []).append(a)
new_abc = [ [ ' '.join(d.pop(b)), b ] for a, b in abc if b in d ]

但正如@Sayse 已经指出的那样,这也将结合'o''from''of'

[['buy', 'contract_type'], ['apple', 'product'], ['from of', 'o'],
 ['Alex heeb', 'trader_name'], ['APPLE INC', 'counter_party']]

【讨论】:

    【解决方案2】:

    试试这个:

    from itertools import groupby    
    
    abc = [
    ["buy", "contract_type"], ["apple", "product"], ["from", "o"],
    ["Alex", "trader_name"], ["heeb", "trader_name"], ["of", "o"],
    ["APPLE", "counter_party"], ["INC", "counter_party"]]
    
    new= [] 
    for k, g in groupby(sorted(abc, key=lambda x:x[1]),key =lambda x:x[1]): 
        new.append(['',k]) 
        for i in g: 
            new[-1][0] += i[0]+ ' '
    

    new 将是您的预期输出:

    [['buy ', 'contract_type'],
     ['APPLE INC ', 'counter_party'],
     ['from of ', 'o'],
     ['apple ', 'product'],
     ['Alex heeb ', 'trader_name']]
    

    【讨论】:

    • 这会为每个第一个元素添加空格。它也弄乱了项目的原始顺序。不知道两者是否相关,但至少值得一提。
    猜你喜欢
    • 2019-02-14
    • 2012-05-23
    • 2020-09-04
    • 1970-01-01
    • 2021-11-10
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多