Home > database >  how to group list and print them out in python
how to group list and print them out in python

Time:11-11

I need to make a function named f3Groups() that accepts one argument. As well as a list named cgList to represent the whole class, containing 3 lists representing the 3 groups. cgList can be an empty list but there cannot be any empty group, for example cgList = [] when there is no student in this class. Return the cgList but I have no idea how to do that. So far I have only made a function printing out list of user inputs.

def get_student_list():
    stdlist = []

    while True:
        iStr = input('Please enter a new student name, ("quit" if no more student)')
        if iStr == "quit":
            return stdlist
        if iStr == "":
            print("Empty student name is not allowed.")
        else:
            stdlist.append(iStr)


stdList = get_student_list()
print("The whole class list is")
for x in stdList:
    print(x, end=' ')
``


I want 7 user inputs. User input 1, 4 and 7 in one list group. User input 2 and 5 in one group. User input 3 and 6 in one group. After that print them horizontally.

``The whole class list is ['Student a', 'Student b', 'Student c', 'Student d', 'Student e'. 'Student f', 'Student g']
Group 1: ['Student a', 'Student d', 'Student g']
Group 2: ['Student b', 'Student e']
Group 3: ['Student c', 'Student f']
`
The above is the output I want. Is there a way to do it?

CodePudding user response:

here is the code you're after:

def get_student_list():
    stdlist = []
    while True:
        iStr = input('Please enter a new student name, ("quit" if no more student)')
        if iStr == "quit":
            return stdlist
        if iStr == "":
            print("Empty student name is not allowed.")
        else:
            stdlist.append(iStr)

def get_group_list(stdList):
    group1 = [stdList[0], stdList[3], stdList[6]]
    group2 = [stdList[1], stdList[4]]
    group3 = [stdList[2], stdList[5]]
    grpList = [group1, group2, group3]
    return grpList



stdList = get_student_list()
grpList = get_group_list(stdList)
print("The whole class list is", stdList)
for i in range(len(grpList)):
    print("Group "   str(i), grpList[i])

As you can see, to print a list after a string horizontally, just add a comma and then the variable after the string.

a_list = [item1, item2]
print("A list: ", a_list)

Prints:

A list: [item1, item2]

Additionally, to get the students into groups use nested lists as a simple solution. This involves lists within lists. Students can be allocated with indices.

CodePudding user response:

I want 7 user inputs.

Then you don't need a while True loop you just need to iterate until you reach 7. For that you can use a while i < 8 loop. And set i = 1

User input 1, 4 and 7 in one list group. User input 2 and 5 in one group. User input 3 and 6 in one group.

In your for loop you can use the i variable to check which group you should place the student in.

After that print them horizontally.

Then you can just print them out individually after the function returns.

def f3Groups():
    stdlist = [[],[],[]]  # three groups so 3 lists
    i = 1
    while i < 8:
        iStr = input('Please enter a new student name, ("quit" if no more student)')
        if iStr == "quit":
            return stdlist
        if iStr == "":
            print("Empty student name is not allowed.")
        else:   
            if i in [1,4,7]:
                 stdlist[0].append(iStr)
            elif i in [2,5]:
                 stdlist[1].append(iStr)
            else:
                 stdlist[2].append(iStr)
            i =1   # increase i by one when student is added.
       return stdlist


stdList = f3Groups()
for i, x in enumerate(stdList):
    print(f"Group {i 1}: {x}")

output

Group 1: ['Student a', 'Student d', 'Student g']
Group 2: ['Student b', 'Student e']
Group 3: ['Student c', 'Student f']

If alternatively you wanted to add a student to each list one by one so they all remain as close to the same length as possible. you could do it like this.

def get_student_list():
    stdlist = []
    while True:
        iStr = input('Please enter a new student name, ("quit" if no more student)')
        if iStr == "quit":
            return stdlist
        if iStr == "":
            print("Empty student name is not allowed.")
        else:
            stdlist.append(iStr)


def f3Groups(stdlist):
    groups = [[],[],[]]
    for i,x in enumerate(stdlist):
        if i % 3 == 0:
            groups[0].append(x)
        if i % 3 == 1:
            groups[1].append(x)
        else:
            groups[2].append(x)
   return groups



stdlist = get_student_list()
groups = f3Groups(stdlist)
for i, x in enumerate(stdlist):
    print(f"Group {i 1}: {x}")

creates the same output as previous example.

  • Related