Skip to main content
 首页 » 编程设计

python之如何拆分列表元素

2025年05月04日14落叶无声

我必须从文件中读入二维列表。 该文件看起来像:

Jack 32
Perry 12
Tim 14

等等

当我打印列表时,它看起来像:

['Jack 32', 'Perry 12', 'Tim 14'] 

但我需要它看起来像:

['Jack', '32', 'Perry', '12', 'Tim', '14'] 

到目前为止,我的代码如下所示:

with open('filelocation', 'r') as f: 
    content = f.readlines() 
    content = [x.strip('\n') for x in content] 
    print(content) 

请您参考如下方法:

你不能只用空格分割整个文件吗?

>>> with open('filelocation') as f: 
        print(f.read().split()) 
 
['Jack', '32', 'Perry', '12', 'Tim', '14'] 

创建结构只是为了将其扁平化是没有意义的。