Comparing two lists are loaded from files in python
我有2个文件
文件1.TXT
1 2 3 4 | 2C:E4:12:B2:EC:4B;20120731_10:06:36;20151005_13:44:51;195.116.227.97 2C:E4:12:B2:26:E0;20120902_21:48:58;20151005_17:01:10;195.116.227.97 E8:BE:81:87:76:10;20131006_20:23:44;20151004_23:56:37;195.116.227.97 ..... |
文件2.TXT
1 2 3 4 5 | C8:91:F9:98:13:4B;2015/09/24 13:30:53 E8:BE:81:87:76:10;2015/09/24 13:30:41 7C:03:D8:3A:BF:14;2015/09/24 13:32:35 18:1E:78:E9:6E:C6;2015/09/24 13:33:46 ..... |
如果file1中的第一列(mac)在file2中,我想从file2中获取所有行并打印,因此在这种情况下输出将是:
1 | E8:BE:81:87:76:10;2015/09/24 13:30:41 |
我不知道如何在python中比较列表
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env python list = {} list1 = {} file = open('file.txt','r') for line in file: mac,first,last,ip = line.split(';') list = mac file1 = open('file1.txt','r') for line in file1: mac,data = line.split(';') list1 = mac,data # ........ |
现在是什么?
首先将文件1中的所有MAC地址存储在一个集合中;现在可以针对该集合测试第二个文件:
1 2 3 4 5 6 7 | with open('file1.txt', 'r') as inf: mac_addresses = {line.partition(';')[0] for line in inf} with open('file2.txt', 'r') as inf: for line in inf: if line.partition(';')[0] in mac_addresses: print(line.strip()) |
我使用集合理解来构建
需要