繁体   English   中英

连接两个彼此对应的列表以创建一个类对象列表

[英]Joining two lists that correspond to each other to create a list of class objects

我正在尝试创建一个包含未指定用户数量的用户名和密码的列表。 我试图使该列表包含“用户”类型的类对象,该类对象包括在下面:

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'

简而言之,我想转一下:

usernames = [John, Tim, Scott]
passwords = [password, password1, password2]

到这个:

userInfo = [(John, password), (Tim, password1), (Scott, password2)]

下面的代码是我到目前为止所拥有的。 这将创建一个包含用户名的列表和一个包含密码的列表。 我想找到一种将用户名列表与相应密码结合起来的方法。

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

任何人都可以提供的任何帮助将不胜感激!

您可以压缩两个列表,然后创建对象:

users = [User(user, password) for user, password in zip(usernameList, passwordList)]

编辑

尽管您在读取数据时将数据解压缩,然后又想将其压缩,但我认为这有点浪费时间,因为数据是您需要的列表列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM