简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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