Python split()函数

2024-09-22 16:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,我只是想了解一些事情

我得到了一堆要打开的txt文件,其中包含数千个单词,全部用空格分隔,我相信我在下面的代码中已经涵盖了这一点。。但我只是想知道如何将这些行分解成3块或用户输入的一些int

['perfect', 'dealing', 'crave', 'stirring', 'expedition', 'alexandria', 'vanish', 'dealing', 'crave']

[['perfect', 'dealing', 'crave'], ['stirring', 'expedition', 'alexandria'],['vanish', 'dealing', 'crave']]

甚至回到列表的形式

a
b
c

短暂性脑缺血发作

word_list=[]
filename = "filename.txt"
with open(filename,"r") as file_object:
    for line in file_object:
        word_list=line.split()
        print(word_list)
    return(word_list)

Tags: txtobjectlinefilenamelistwordfiledealing
3条回答

使用itertools配方中的grouper构造:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x')  > ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

您的代码是:

word_list = []
n = 3
filename = "filename.txt"
with open(filename, "r") as file_object:
    for line in file_object:
        word_list.append(grouper(line.split(), n))
return word_list

您可以使用for i in range(0, len(word_list), 3)在间隔为3的列表上迭代,并使用索引对原始列表进行切片

new_list = [word_list[i:i+3] for i in range(0, len(word_list), 3)]
# [['perfect', 'dealing', 'crave'], ['stirring', 'expedition', 'alexandria'], ['vanish', 'dealing', 'crave']]

您不是在更新word_list,而是过度写入了它的值,它应该是这样的

word_list=[]
filename = "filename.txt"
with open(filename,"r") as file_object:
    for line in file_object:
        word_list.append(line.split()) # notice this
        print(word_list)
    return(word_list)

sub_list_size = 3; # take from user input or as needed
output = [word_list[i: i+sub_list_size] for i in range(0, len(word_list), sub_list_size)]
print(output)

相关问题 更多 >