python - 根据嵌套列表python中的类别计算用户

标签 python python-3.x list dictionary

我有一个包含两个子列表的列表。 这里看起来像这样

a = [['user1', 'referral'], ['user2', 'referral'], ['user1', 'referral'], ['user1', 'affiliate'], ['user7', 'affiliate'], ['user1', 'affiliate'], ['user9', 'affiliate'], ['user4', 'cpc'], ['user4', 'referral'], ['user2', 'referral'], ['user7', 'affiliate'], ['user14', 'cpc'], ['user3', 'orgainic'], ['user2', 'orgainic'], ['user4', 'cpc'], ['user2', 'cpc'], ['user8', 'cpc'], ['user2', 'orgainic']]

我想根据类别计算用户(唯一)。

必需:

required = [['referral',3],['affiliate',3],['cpc',4],['orgainic',2]]

我得到的输出:

{'referral': 3, 'affiliate': 2, 'cpc': 4, 'orgainic': 3}

数错了。

这是我试过的代码:

a = [['user1', 'referral'], ['user2', 'referral'], ['user1', 'referral'], ['user1', 'affiliate'], ['user7', 'affiliate'], ['user1', 'affiliate'], ['user9', 'affiliate'], ['user4', 'cpc'], ['user4', 'referral'], ['user2', 'referral'], ['user7', 'affiliate'], ['user14', 'cpc'], ['user3', 'orgainic'], ['user2', 'orgainic'], ['user4', 'cpc'], ['user2', 'cpc'], ['user8', 'cpc'], ['user2', 'orgainic']]

required = [['referral',3],['affiliate',3],['cpc',4],['orgainic',2]]

c = {}
visits = []
for i in a:
    # print(i)
    for j in i[1:]:
        if j not in c and i[0] not in visits:
            c[j] = 1
            visits.append(i[0])
        elif j in c and i[0] not in visits:
            c[j] = c[j]+1
print(c)

帮我解决一些问题...

最佳答案

这是一种使用 collections.defaultdict 的方法。

例如:

from collections import defaultdict

a = [['user1', 'referral'], ['user2', 'referral'], ['user1', 'referral'], ['user1', 'affiliate'], ['user7', 'affiliate'], ['user1', 'affiliate'], ['user9', 'affiliate'], ['user4', 'cpc'], ['user4', 'referral'], ['user2', 'referral'], ['user7', 'affiliate'], ['user14', 'cpc'], ['user3', 'orgainic'], ['user2', 'orgainic'], ['user4', 'cpc'], ['user2', 'cpc'], ['user8', 'cpc'], ['user2', 'orgainic']]
result = defaultdict(int)
seen = set()
for k, v in a:
    key = "{}_{}".format(k, v)
    if key not in seen:
        result[v] += 1
        seen.add(key)
print(list(map(list, result.items())))

输出:

[['referral', 3], ['affiliate', 3], ['cpc', 4], ['orgainic', 2]]

关于python - 根据嵌套列表python中的类别计算用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374895/

相关文章:

python - TypeError : strptime() argument 1 must be string, 不 float

python - 如何并行化需要多个常量的函数?

python - 如何在 BeautifulSoup 中返回标签的元素?

html - CSS 列表样式下拉菜单定位

python - 使用 Elasticsearch python API执行查询时出错

python - 使用 DatetimeIndex 重新采样 DataFrame 并保留日期范围

python - 关于修改python列表的初学者问题

python - 添加列表和迭代器以形成新列表

list - 使用 Red 语言从多个列表中获取值到一个列表

python - 重置 pandas 行索引以从 0 以外的数字开始?