python - 从列表中删除重复项并检查 IP 是否来自一个列表中的另一个列表

标签 python python-3.x csv duplicates

我必须 csv 文件。 第一个看起来像这样:

enter image description here

第二个包含 IP 列表:

139.15.250.196
139.15.5.176

我想检查第一个文件中的任何给定 IP 是否在第二个文件中。这似乎可以工作(如果我的代码被破坏,请更正或提供提示),但问题是第一个文件包含许多重复的值,例如10.0.0.1 可能出现 x 次,但我无法找到删除重复项的方法。您能帮助我或指导吗?

import csv

filename = 'ip2.csv'
with open(filename) as f:
    reader = csv.reader(f)
    ip = []
    for row in reader:
        ip.append(row[0])


filename = 'bonk_https.csv'
with open(filename) as f:
    reader = csv.reader(f)
    ip_ext = []
    for row in reader:
        ip_ext.append(row[0])
        for a in ip:
            if a in ip_ext:
                print(a)

最佳答案

您可以使用 set(list) 将任何列表转换为集合。集合仅包含其中一项,并且可以像列表一样与集合中的成员进行比较。因此,只需将您的 ip 列表转换为一组即可。

with open(filename) as f:
    ip_ext = []
    for row in reader:
        ip_ext.append(row[0])
        for a in set(ip):
            if a in set(ip_ext): #well, you don't need a set her unless you also have duplicates in ip_ext
                print(a)

或者,如果您找到了条目,则中断/继续。 This might help you with that

关于python - 从列表中删除重复项并检查 IP 是否来自一个列表中的另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713326/

相关文章:

python - 将 3 列数据框转换为矩阵

python - 使用 Python for Facebook 进行搜索

python - 为什么我使用 exec() 会得到 "NameError: name is not defined"?

javascript - 将 DB 从 latin1 编码字符串导出为 CSV 到 utf-8

python - 更改 matplotlib 样式表中的颜色数量

python - Celery是否使用链和组组合的结果后端?

python - 推荐系统 - 基于 Softmax 的深度神经网络模型中的用户嵌入

python - pyqt5选项卡区域未填充整个可用空间

r - 在导出为 .csv 文件之前加入两个数据框

python - Bcp 命令进入 Microsoft Azure