【问题标题】:Multidicts and SetsMultidicts和集合
【发布时间】:2015-07-23 15:39:42
【问题描述】:

我有 n csv,我用它创建了一个 multidict:

for name in filenames:
    with open(path+name) as openFile:
    reader = csv.reader(openFile)
    for line in reader:
        if line[1] in t:
            pass
        elif line[1] == 'filer_name':
            pass
        else:
            t[name[:-8]].add(line[1])

这可以工作并输出一个多字典(从集合导入默认字典),格式如下:

{company name: {other_company_1, other_company_2,...}}

有 n 家公司和 n 组其他公司。所以现在,我想说对于每个键中的 other_company,检查 other_company 是否在另一家公司的值中。示例:

defaultdict(<class 'set'>, {Apple : {Samsung, Qualcomm, NVidia}},{Microsoft: {Samsung, Alcoa, Dollar Tree}})

我希望返回三星,但它需要为每个键搜索每组值。因此,如果 Dollar Tree 在第三家公司的价值观中,它也会找到 Dollar Tree。

尝试解决方案:

for key, values in t.items():
    for item in values:
        if item in values:
            print(item)

此外,如果other_company 出现 3 次或更多次,有没有办法返回它? 4次或更多?米或更多次?在multidict中。

干杯!

【问题讨论】:

    标签: python python-3.x dictionary set


    【解决方案1】:

    使用计数器:

    from collections import Counter
    cnt = Counter()
    for key, values in t.items():
        for item in values:
            cnt[item] += 1
    
    print([comp for comp in cnt if cnt[comp] > 1])
    

    如果要出现 N 次,可以将 1 更改为 2,3。

    【讨论】:

    • 我试过这个;不幸的是,它不起作用。它返回: at 0x00...92B8AF8>.
    • @xp1123 :忘记添加 [] 来制作列表。试试新版本。
    • 没关系。当列表位于 print 语句中时,它可以工作。谢谢!
    • 您不需要内部的for 循环。只需cnt.update(items)
    • 你也不需要for key, values in t.items():,因为你从不使用key
    【解决方案2】:

    您需要比较作为主字典值的每对公司集,以便您可以使用 itertools.combinations 来创建这些对,然后使用 set.intersection 检查交集以返回交集。

    for (comp1,comp_set1),(comp2,comp_set2) in combinations(mydict.items(),2) :
         print '{} and {}'.fromat(com1,com2),comp_set1.intersections(comp_set2)
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多