在python 3中水平显示列表结果而不是垂直

时间:2017-10-17 22:38:55

标签: python python-3.x

我在python中创建了一个函数来计算单词的长度,同时忽略标点符号。例如,如果我有句子:"Haven't there been 3 blackouts today?结果应该如下:[6,5,4,1,9,5]我可以使用我创建的以下函数获得这些结果:

import string
def word_length_list(given_string):
        clean_string = given_string.translate(str.maketrans('','',string.punctuation))
        word_lenght_list = list(map(len, clean_string.split()))
        return word_lenght_list
    given_string = "Haven't there been 3 blackouts today?"
    word_length_list(given_string)

此函数为我提供了预期的结果:[6, 5, 4, 1, 9, 5] 但是如果我给它一个非常长的字符串,例如:

given_string = "Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function.Testing the output of the function."

它以下列方式给我结果:

[7,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 15,
 3,
 6,
 2,
 3,
 8]

有没有人有任何关于如何使我的列表水平返回短字符串和长字符串的想法?任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:3)

在单独的单元格中运行命令%pprint

这会打开漂亮的打印。该列表现在将水平显示。

答案 1 :(得分:0)

', '

加入列表项的表示形式
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))

输出:

3.14, 'string', ('tuple', 'of', 'items')