我正在编写一个名为apply_to_list的函数,它使用现有函数sort_words获取字符串列表,并按字母顺序将每个字符串打印出来。目前,我的输出不在列表中,每个字符串都不在引号内
预期:将[“香蕉苹果”、“猫象狗”]变成[“苹果香蕉”、“猫象狗”]
我的输出:
apple banana
cat dog elephant
代码:
def sort_words(string):
words = string.lower().split()
# sort the list
words.sort()
newSentence = " ".join(words)
# Return newSentence
return newSentence
def apply_to_list(string_list):
for string in string_list:
strings = sort_words(string)
print(strings)
apply_to_list(["banana apple", "cat elephant dog"])
我在你的问题中理解的是,你想要实现这一点:
输出
您可以添加其他功能并在打印时使用:
我想说,当您尝试在
sort_words
中连接字符串时,您正在将列表转换为字符串,因此您返回的值将不是列表。所以我建议您创建sort_words
返回值的列表我已经在下面展示了这是如何可能的
输出
相关问题 更多 >
编程相关推荐