[英]Joining two lists that correspond to each other to create a list of class objects
I am trying to create a single list that contains the username and password of an unspecified amount of users. 我正在尝试创建一个包含未指定用户数量的用户名和密码的列表。 I am trying to make this list contain class objects of type "User", which is included below:
我试图使该列表包含“用户”类型的类对象,该类对象包括在下面:
import datetime
import sys
class User:
global_count = 0
def __init__(self, username, key):
self.username = username
self.key = key
User.global_count += 1
def showGlobalCount(self):
print "Number of Keys: %d" % global_count
def showKeys(self):
print "username: " + self.username
print "key: " + self.key + '\n'
Simply put, I would like to turn this: 简而言之,我想转一下:
usernames = [John, Tim, Scott]
passwords = [password, password1, password2]
into this: 到这个:
userInfo = [(John, password), (Tim, password1), (Scott, password2)]
The code below is what I have so far. 下面的代码是我到目前为止所拥有的。 This creates a list that contains the usernames, and a list that contains the passwords.
这将创建一个包含用户名的列表和一个包含密码的列表。 I want to find a way to combine the username list with the corresponding passwords.
我想找到一种将用户名列表与相应密码结合起来的方法。
from Credentials import *
def main():
with open("Info.txt", "r") as infile:
data = [line.rstrip().split(",") for line in infile]
usernames, passwords = zip(*data)
usernameList = []
passwordList = []
for user in usernames:
usernameList.append(user)
for key in passwords:
passwordList.append(key)
print usernameList,passwordList
if __name__ == "__main__":
main()
Any help anyone can provide would be much appreciated!! 任何人都可以提供的任何帮助将不胜感激!
You can zip the two lists and then create the objects: 您可以压缩两个列表,然后创建对象:
users = [User(user, password) for user, password in zip(usernameList, passwordList)]
edit 编辑
although you unzip the data when reading it, and then want to zipped again, I think it's a little waste of time, because data is the list of lists that you need 尽管您在读取数据时将数据解压缩,然后又想将其压缩,但我认为这有点浪费时间,因为数据是您需要的列表列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.