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

2024-09-27 07:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

我正在把文件读成一个单子。 然后定位“username”位置并使用enumerate查找该位置

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']

这样我就可以把它和安全用户列表进行比较


Tags: the用户列表配置文件usernamepasswordusers用户名
3条回答

对你的代码做了一些修改

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']

请尝试以下操作:

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])

使用正则表达式。你知道吗

例如:

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']

相关问题 更多 >

    热门问题