4

Python 碰到一题,大家有没有更好的解法

 3 years ago
source link: https://www.v2ex.com/t/791154
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

Python 碰到一题,大家有没有更好的解法

  wuwukai007 · 2 天前 · 1848 次点击
nput_data = [
    ['格力', '格力电器'],
    ['格力', '美的', '格力电器', '美的集团'],
    ['中国民生投资股份有限公司', '中民投'],
    ['格力', '格力电器', '格力集团'],
    ['工银', '中信证券', '工行', '中国工商银行'],
    ['建行', '建设银行', '北大光华'],
    ['中国银行', '工行', '工商银行', '港交所'],
    ['中行', '建行', '工行', '中金', '工商银行', '中国银行', '建设银行'],
    ['农行', '建设银行', '建行', '中行'],
    ['中国民生投资股份有限公司', '上海金融法院', '中民投', '启信宝']
]
输出:
            {('格力', '格力电器'): 3,
             ('美的', '美的集团'): 1,
             ('中民投', '中国民生投资股份有限公司'): 2,
             ('格力', '格力集团'): 1,
             ('工银', '中国工商银行'): 1,
             ('建行', '建设银行'): 3,
             ('中行', '中国银行'): 2,
             ('工银', '工商银行'): 2}


from itertools import chain
from collections import defaultdict

data = list(chain(*nput_data))
res = [set(i) for i in data]

count = defaultdict(int)
for index,row in enumerate(res):
    for index2,i in enumerate(res):
        if row.issuperset(i) and row != i:
            count[(data[index2],data[index])] += 1
            break
        

第 1 条附言  ·  1 天前

原题就是 
nput_data = [xx] ,
结果是: 
('格力', '格力电器'): 3, 
('格力', '格力集团'): 1, 等,请补全结果,
我也是嗯做,然后说是 key 全包含另一个 key 作为一个分类,
统计所有分类数量
key1 全包含 key2 就算一类,例如 '中国民生投资股份有限公司' 包含 '中民投'

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK