如何比较两个列表并在一个列表中打印差异

时间:2019-07-03 07:04:16

标签: python list set comparison

我正在尝试从配置文件中提取用户名到一个列表中,并将用户名与另一个安全的用户名列表进行比较。 配置文件如下所示:

username Hilton privilege 15 password 0 $xxxxxxxxxxxxx
username gooduser password 0 $xxxxxxxxxxxxx
username jason secret 5 $xxxxxxxxxxxxx

输出问题不是单个列表! (每个用户都在列表中)

['Hilton']
['gooduser']
['jason']

我正在将该文件读取到一个列表中。 然后找到“用户名”位置,并使用枚举找到该位置

the_list = []

with open('config_file.txt', "r") as f:
    the_list = f.read().split()        
    print(the_list)
    find_keyword = 'username'

    secure_users = ['jason','test','admin']

for i,x in enumerate(the_list):   # search in the list
  if x=='username':               # for this keyword 'username'
     pos = i + 1                  # position of every username 

     print(the_list[pos].split())          # print all users.

#Compare secure_users[] vs the_list[] here

预期输出为>> ['Hilton','gooduser','jason']

之类的列表

以便我可以将其与secure_users列表进行比较

4 个答案:

答案 0 :(得分:1)

尝试以下操作:

usernames = []
secure_users = ['jason','test','admin']
with open('config_file.txt', "r") as f:
    for line in f:
        usernames.append(line.split()[1])

print([user for user in secure_users if user in usernames])

答案 1 :(得分:0)

对您的代码进行了一些修改,

the_list = []

with open('config_file.txt', "r") as f:
    the_list = f.read().split()        
    print(the_list)
find_keyword = 'username'

secure_users = ['jason','test','admin']

users_list = []
for i,x in enumerate(the_list):   # search in the list
    if x=='username':               # for this keyword 'username'
        pos = i + 1                  # position of every username 

        users_list.append(the_list[pos].split()[0])          # print all users
print(users_list)

输出:

['username', 'Hilton', 'privilege', '15', 'password', '0', '$xxxxxxxxxxxxx', 'username', 'gooduser', 'password', '0', '$xxxxxxxxxxxxx', 'username', 'jason', 'secret', '5', '$xxxxxxxxxxxxx']
['Hilton', 'gooduser', 'jason']

另一种解决方案:(最佳方式)

with open('config_file.txt', 'r') as f:
    data = f.read().split()
    user_names = [data[i+1] for i,line in enumerate(data) if 'username' in line ]

输出:

['Hilton', 'gooduser', 'jason']

答案 2 :(得分:0)

使用正则表达式。

例如:

import re

find_keyword = 'username'
the_list = []
with open('config_file.txt') as f:
    for line in f:
        m = re.search(r"\b{}\b \b(.*?)\b ".format(find_keyword), line.strip())    #Search for key and word after that. 
        if m:
            the_list.append(m.group(1))

print(the_list)# ->['Hilton', 'gooduser', 'jason']

答案 3 :(得分:0)

在您的代码中添加一个名为diff的列表,例如:

diff = []

然后只需在代码行打印(the_list [pos] .split())之后添加以下两行:

if the_list[pos] not in secure_users:
        diff.append(the_list[pos])

然后打印差异以查看单个列表:

print(diff)