比较 Python 中的多个列表
Compare many lists in Python
我有 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
使用 itertools
和 pandas
你可以:
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
使用 Counter
class 来计算 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)
如果您想要 key/value 对出现不止一次的项目:
more_than_once = {k:v for k,v in ctr.items() if v>1}
print(more_than_once)
我有 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
使用 itertools
和 pandas
你可以:
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
使用 Counter
class 来计算 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)
如果您想要 key/value 对出现不止一次的项目:
more_than_once = {k:v for k,v in ctr.items() if v>1}
print(more_than_once)