简体   繁体   中英

Error while using choice method from random module in python

I was doing a small project to randomly change the surname among the names taken as input from the user.

def randomize(names):
    import random
    firstname = []
    surname = []
    n = 0
    for j in range(len(names)):
        name1 = names[j].split()
        firstname.append(name1[0])
        surname.append(name1[1])
    print(firstname)
    print(surname)
    while n < len(names):
        firstname = random.choice(firstname)
        surname = random.choice(surname)
        n += 1
        print(firstname + " " + surname)


if __name__ == '__main__':
    name = []
    number = int(input("Enter the number of students\n"))
    for i in range(number):
        name.append(input("Enter the names\n"))
    randomize(name)

It is working first at the first time but from the second line it is only printing letters repeatadly.

def randomize(names):
    import random
    firstname = []
    surname = []
    n = 0
    for j in range(len(names)):
        name1 = names[j].split()
        firstname.append(name1[0])
        surname.append(name1[1])
    while n < len(names):
        firstname1 = random.choice(firstname)
        firstname.remove(firstname1)
        surname1 = random.choice(surname)
        surname.remove(surname1)
        print(firstname1 + " " + surname1)
        n += 1


if __name__ == '__main__':
    name = []
    number = int(input("Enter the number of students\n"))
    for i in range(number):
        name.append(input("Enter the names\n"))
    randomize(name)

Got it. Thank you for looking into this. It was due to my hurry that I missed a small detail. I got the answer when I read it again.

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