【问题标题】:Nested list or two dimensional array in PythonPython中的嵌套列表或二维数组
【发布时间】:2020-03-22 12:05:41
【问题描述】:



我有一个 IP 地址列表。我需要将这些 IP 地址存储在列表或数组中(不允许重复)并存储它们的计数。

例如我有

IP-1
IP-4
IP-7
IP-4
IP-2
IP-4
IP-2

此列表来自 .txt 文件。我有多个这样的文件,所以我不能像这样将list = [ [a,b], [c,d], [e,f] ] 放在代码中(我的意思是不要在代码中静态地这样做,因为对于每个 .txt 文件,列表都会不同)。

所以在这个列表中我有:
IP-1   1x
IP-4   3x
IP-7   1x
IP-2   2x

我必须以某种方式将其全部存储在一个列表或数组中。例如像这样:

list_of_ips_and_their_counts = [ [IP-1,1], [IP-4,3], [IP-7,1], [IP-9,2] ]

现在我必须在此列表/数组中搜索出现次数最多的 IP 并将其打印出来。例如:

print("IP address " + the_ip + " occured " + number + " times.") # IP address IP-4 occured 3 times.


我不确定如何存储 IP 地址及其计数。

【问题讨论】:

  • 是数组还是numpy数组?
  • 有pandas扩展数组存储IP地址。它没有为您提供存储计数的直接解决方案(您可以使用 Pandas 方法来做到这一点),但它确实有一些不错的 IP 相关方法github.com/ContinuumIO/cyberpandas
  • 你试过什么?你做过研究吗?

标签: python arrays list multidimensional-array nested-lists


【解决方案1】:

您可以使用collections.Counter 计算文件中的每个IP-{number} 行:

from collections import Counter

with open("test.txt") as f:
    ip_counts = Counter(line.strip() for line in f)
    # Counter({'IP-4': 3, 'IP-2': 2, 'IP-1': 1, 'IP-7': 1})

    for ip_address, count in ip_counts.items():
        print("IP address %s occured %d times" % (ip_address, count))

输出:

IP address IP-1 occured 1 times
IP address IP-4 occured 3 times
IP address IP-7 occured 1 times
IP address IP-2 occured 2 times 

如果您愿意,也可以使用map() 来计算行数:

ip_counts = Counter(map(str.strip, f))

注意:这里使用str.strip() 去除键中的空格,例如将'IP-1\n' 转换为IP-1。由于您不需要包含空格,因此将来可以更轻松地访问密钥。

如果您想要最大计数,我会使用 max() 和 operator.itemgetter():

print(max(ip_counts.items(), key=itemgetter(1)))
# ('IP-4', 3)

使用索引1 处的计数返回最大元组。

【讨论】:

    【解决方案2】:

    您可以使用np.argmax() 完成此操作。这是你问题的第二步。但最好每个线程都问一个问题。

    import numpy as np
    
    result = ip[np.argmax(np.array(ip)[:, 1])]
    print("IP address " + result[0] + " occured " + str(result[1]) + " times.")
    
    Out[114]: IP address IP-4 occured 3 times.
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2011-05-03
      相关资源
      最近更新 更多