【问题标题】:Compare many lists in Python比较 Python 中的许多列表
【发布时间】:2021-12-14 09:10:08
【问题描述】:

我有 7 个带有 IP 地址的列表:

    list_1 = ['192.168.0.1', '77.1.15.2', '30.24.15.7', '8.8.8.8', '5.6.13.8']
    list_2 = ['12.38.75.64', '30.24.15.7', '192.168.0.1']
    list_3 = ['6.15.79.64', '15.127.17.4', '192.168.0.1', '0.0.0.0', '74.58.69.14']
    list_4 = ['45.54.45.54', '89.98.89.98', '192.168.3.7', '192.168.4.12']
    list_5 = ['192.168.8.1', '192.168.0.1', '30.24.15.7', '192.168.7.24']
    list_6 = ['192.168.8.2', '192.168.8.3', '192.168.8.4', '15.127.17.4', '192.168.0.1']
    list_7 = ['192.168.0.1', '8.8.8.8']

如何比较所有列表并获取多次出现的 IP,以及这些 IP 的出现次数? IP 计数 192.168.0.1 = 6 30.24.15.7 = 3 8.8.8.8 = 2 15.127.17.4 = 2

【问题讨论】:

  • 您是否尝试获取所有列表中每个 IP 的唯一出现次数?
  • 使用itertools.chain() 将多个列表组合成一个迭代器,使用collections.Counter() 生成item:count 的字典

标签: python compare


【解决方案1】:

使用Counter 类计算 IP:

from collections import Counter
ctr = Counter()
ctr.update(list_1)
ctr.update(list_2)
# [...] repeat for all lists

# [...] Use the counts as needed
print(ctr)

如果您想要多次出现的项的键/值对:

more_than_once = {k:v for k,v in ctr.items() if v>1}
print(more_than_once)

【讨论】:

    【解决方案2】:

    使用itertoolspandas 你可以这样做:

    import itertools
    import pandas as pd
    
    # chain all lists
    l = list(itertools.chain(list_1, list_2, list_3, list_4, list_5, list_6, list_7))
    
    # convert them to a Pandas Series and count values
    counts = pd.Series(l).value_counts()
    
    # only multiple occurrences
    greaterThan1 = counts[counts>1]
    

    并显示greaterThan1 你会得到:

    192.168.0.1    6
    30.24.15.7     3
    15.127.17.4    2
    8.8.8.8        2
    

    【讨论】:

    • 如果你不想安装 pandas,collections.Counter() 会从列表中生成一个 dict 的项目计数。
    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2018-03-19
    相关资源
    最近更新 更多