Python如何将函数输出字符串改为纵向单列显示,嵌套函数可写双for循环吗
问题1:修改输出为每个姓名单独占一行
问题原因
现有代码里的listToString函数用空格作为分隔符拼接列表元素,所以输出是单行空格分隔的内容,要实现单行一个名字,只需把分隔符替换为换行符\n即可。另外原代码中student_list函数里return之后的print(name)属于死代码,永远不会执行,可以直接删除。
修正后的代码
def student_list(names): unique = [] for name in names: if name not in unique: unique.append(name) return unique def listToString(names): # 把拼接用的空格替换为换行符\n str1 = "\n" return str1.join(names) names = ["Adam", "Ben", "Aaron", "Clyde", "Alex", "Billy", "Chris", "Adam", "Clyde"] names.sort() print(listToString(student_list(names)))
简化写法
如果不需要保留listToString函数,也可以直接遍历去重后的列表逐行打印:
names = ["Adam", "Ben", "Aaron", "Clyde", "Alex", "Billy", "Chris", "Adam", "Clyde"] unique_names = [] # 先排序再去重 for name in sorted(names): if name not in unique_names: unique_names.append(name) # 逐行输出 for name in unique_names: print(name)
问题2:嵌套函数内部是否可以编写两个for循环
可以,函数内部的循环数量没有任何限制,不管是不是嵌套函数,只要符合业务逻辑,写任意数量的for循环都可以。
参考示例:
def outer_func(): # 定义嵌套函数 def inner_func(): # 第一个for循环 for i in range(3): print(f"第一组循环值:{i}") # 第二个for循环 for j in range(2): print(f"第二组循环值:{j}") inner_func() outer_func()
内容的提问来源于stack exchange,提问作者S7YF4WX
相关产品推荐
相关产品推荐

