如何在python中对列表进行分组并打印出来

rsl1atfo  于 2022-12-10  发布在  Python
关注(0)|答案(2)|浏览(289)

我需要创建一个名为f3Groups的函数(),它接受一个参数。还有一个名为cgList的列表来表示整个类,它包含3个列表来表示3个组。cgList可以是空列表,但不能有任何空组,例如cgList = [],当这个班级没有学生时。返回cgList,但是我不知道如何做。到目前为止,我只做了一个打印用户输入列表的函数。

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?
webghufk

webghufk1#

下面是您需要的代码:

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

如您所见,要在字符串后面水平打印列表,只需在字符串后面添加一个逗号和变量。

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

印刷品:

A list: [item1, item2]

此外,要将学生分成小组,使用嵌套列表是一个简单的解决方案。这涉及到列表中的列表。学生可以分配索引。

w6lpcovy

w6lpcovy2#

我需要7个用户输入。
那么你不需要while True循环,你只需要迭代到7,你可以使用while i < 8循环,并设置i = 1
用户在一个列表组中输入1、4和7。用户在一个组中输入2和5。用户在一个组中输入3和6。
在for循环中,可以使用变量i来检查应该将学生放在哪个组中。
然后水平打印。
然后,您可以在函数返回后单独打印它们。

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}")

输出功率

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

如果您想将学生逐个添加到每个列表中,使它们尽可能保持相同的长度,您可以这样做。

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}")

创建与上一个示例相同的输出。

相关问题