Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

python 如何计算出现最多的字符串 dict

使用 python 从一组数据中获取 最可能的 地址ID [省份ID,城市ID,区域ID] 的集合。

address_all = {'A': [5, 20, 300], 'C': [1, 50, 600], 'B': [5, 20], 'D': [6, 30, 300]}
# 需要得到的是 [5,20,300]

如何改写以下方法,获取出现次数最多的地址:

def get_most(address_all):
    """

    :param address_all:
    :return:
    """

    # 查找最可能的 id1 id2 id3
    address = []
    id1 = id2 = id3 = 0
    ids = {}
    for x, y in address_all.items():
        if len(y) >= 1 and y[0] > 0:
            ids[y[0]] = ids.get(y[0], 0) + 1
    id1 = sorted(ids.items(), key=lambda d: d[1], reverse=True)[0][0]

    ids = {}
    for x, y in address_all.items():
        if len(y) >= 2 and y[0] == id1 and y[1] > 0:
            ids[y[1]] = ids.get(y[1], 0) + 1
    id2 = sorted(ids.items(), key=lambda d: d[1], reverse=True)[0][0]

    ids = {}
    for x, y in address_all.items():
        if len(y) >= 3 and y[0] == id1 and y[1] == id2 and y[2] > 0:
            ids[y[2]] = ids.get(y[2], 0) + 1
    id3 = sorted(ids.items(), key=lambda d: d[1], reverse=True)[0][0]

    address = []
    if id1:
        address.append(id1)
        if id2:
            address.append(id2)
            if id3:
                address.append(id3)
    return address

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

敢问 你想得到的结果是什么


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...