首页 > 解决方案 > 如何将函数中的字符串转换为“垂直”或列显示?

问题描述

我是新手,这可能是一个新手问题。我正在使用 Python。所以这里是代码:

def student_list (names):
    unique = [ ]
    for name in names:
        if name not in unique:
            unique.append(name)
    return unique
    print(name)        

def listToString(names):
        str1 = " "
        return (str1.join(names))
                
names = ["Adam", "Ben", "Aaron", "Clyde", "Alex", "Billy", "Chris", "Adam", "Clyde"]
names.sort()
    
print(listToString(student_list(names)))

该代码将导致:

亚伦亚当亚历克斯本比利克里斯克莱德

但我想要实现的是:

亚伦
亚当
亚历 克斯

比利克里斯克
莱德

还有一个附带问题,嵌套函数中是否可以有两个 for 循环?

谢谢你。

标签: pythonfor-loopduplicates

解决方案


只需像这样将列表写入字符串函数

def listToString(names):
        str1 = "\n"
        return (str1.join(names))

注意“\n”作为连接字符而不是“”。

要回答第二个问题,是的,一个函数或一个嵌套函数内部可以有任意数量的嵌套循环。


推荐阅读