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

问题描述 投票:5回答:2

我在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]

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

python python-3.x
2个回答
3
投票

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

这变得很漂亮。该列表现在将水平显示。


0
投票

使用', '加入列表项目的表示,

l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))

输出:

3.14, 'string', ('tuple', 'of', 'items')
© www.soinside.com 2019 - 2024. All rights reserved.