![](/img/trans.png)
[英]How would I eliminate spacing, line breaks to have a space-delimited string for each string within my list python
[英]How to split a multiline string with space-delimited integers to a list of lists for each line
有沒有一種簡單的方法可以將多行字符串分成不同大小的不同列表? 我在一個文件中有這個元素:
5 5 6 7 8 9
1 3 4 53 4
1 23
13 312
22 111 123
我想得到一個包含這些元素的數組/列表
list= [5,5,6,7,8,9],[1,3,4,53,4],[1,23],[13,312],[22,111,123]
它必須應用於任何文件(它們總是帶有整數的文件),重要的是它在每個 '\\n' 中划分數組/列表
我想避免使用外部導入(例如 NumPy),我只需要使用 Python 提供的工具來完成。
這很容易。 請記住,文件是可迭代的。
>>> # demo-list that imitates your file
>>> file = '''5 5 6 7 8 9
... 1 3 4 53 4
... 1 23
... 13 312
... 22 111 123'''.splitlines()
>>>
>>> [map(int, line.split()) for line in file]
[[5, 5, 6, 7, 8, 9], [1, 3, 4, 53, 4], [1, 23], [13, 312], [22, 111, 123]]
您可以使用此代碼將文本文件的所有行讀取到列表中,然后從每一行創建一個列表:
with open('path/to/your/file', 'r') as f:
lists = [line.strip().split() for line in f]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.