如何在列表中换行?

时间:2018-08-04 06:19:48

标签: python python-3.x

这是我的代码:

user_input = input("Enter a saying or poem: ")

words_list = user_input.split()

words_list_length = len(words_list)


def word_mixer(words_list):

    words_list.sort()

    final_list = []

    if(len(words_list) <= 5):

        final_list = words_list 


    else:

        while(len(words_list) > 5):

            first_word_popped = words_list.pop(-5)

            final_list.append(first_word_popped)

            second_word_popped = words_list.pop(0)

            final_list.append(second_word_popped)

            third_word_popped = words_list.pop(-1)

            final_list.append(third_word_popped) 

    return final_list

所以我想要的是在while循环的结尾处换行,以便当代码退出while循环时,final_list变量中的元素以3乘3的方式打印(或容纳),因为它附加了每次迭代中包含3个元素。我见过人们使用join()方法,但是我不确定如何在这里实现它,以防万一我应该解决问题。

我已经更新了代码,以便你们可以获得更多的上下文。输入示例为:“您好,这是用户提供的字符串输入”。预期的输出将是:

string given user
Hello this by

如您所见,该字符串已排序,并且应该在每行中打印3个单词(当然,如果我在代码中添加了一条打印语句)。但是我找不到办法。

此练习来自edx.org页面上的Python课程。在那里,他们给出了此输入/输出示例:

enter image description here

只需忽略大写/小写的单词。但是如您所见,通过在列表中添加“ \ n”,列表以3 x 3的形式打印。我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果只想打印,则可以在循环本身内用循环末尾的“ \ n”进行打印。但是,如果要以可以分别使用每组单词的格式存储它,则可以执行以下操作:

words_list = ["Hello", "there", "this", "is", "a", "string", "input", "given", "by", "the", "user"]
final_list_2 = list()
while(len(words_list) > 5):
    final_list = list()
    first_word_popped = words_list.pop(-5)
    final_list.append(first_word_popped)
    second_word_popped = words_list.pop(0)
    final_list.append(second_word_popped)
    third_word_popped = words_list.pop(-1)
    final_list.append(third_word_popped) 
    final_list_2.append(final_list)

for final_list in final_list_2:
    print (" ".join(final_list))

输出:

input Hello user a there the

答案 1 :(得分:0)

因此,您需要为每三个单词添加一个新行,这很简单...

LIST = ["or", "brushed", "thy", "not", "little", "though", "me?", "summers?", "thee?"]
# Insert the new line
for i in range(len(LIST)):
    if i%3==0 and i>0:
        LIST.insert(i, "\n")
# Join the sentence
para = " ".join(LIST)
# Print the result
for i in para.split("\n"):
    print(i.strip())

你会得到的。

or brushed thy
not little
though me? summers? thee?