Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的嵌套列表或二维数组_Python_Arrays_List_Multidimensional Array_Nested Lists - Fatal编程技术网

Python中的嵌套列表或二维数组

Python中的嵌套列表或二维数组,python,arrays,list,multidimensional-array,nested-lists,Python,Arrays,List,Multidimensional Array,Nested Lists,我有一个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-11x IP-43x IP-71x IP-22x 我必须以某种方式将其存储在一个列表或数组



我有一个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-11x
IP-43x
IP-71x
IP-22x

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

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地址及其计数。

您可以使用来计数文件中的每一行
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 
如果愿意,还可以使用来计算行数:

ip_counts = Counter(map(str.strip, f))
注意:在这里用于从键中去除空白,例如将
'IP-1\n'
转换为
IP-1
。这使得将来更容易访问密钥,因为不需要包含空格

如果您想要最大计数,我将使用:


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

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

import numpy as np

result = ip[np.argmax(np.array(ip)[:, 1])]
print("IP address " + result[0] + " occured " + str(result[1]) + " times.")

它是数组还是numpy数组?有一个用于存储IP地址的扩展数组。它并没有为您提供存储计数的直接解决方案(您可以使用Pandas方法来实现),但它确实有一些与IP相关的好方法,您尝试过什么?你做过什么调查吗?
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.