[英]How to split list elements?
我必須從文件中讀取2D列表。 該文件如下所示:
傑克32
佩里12
提姆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']
毫無意義地創建結構只是為了使其扁平化。
使用空格作為分隔符,將['Jack 32', 'Perry 12', 'Tim 14']
每個元素的字符串分割開(默認)。
遍歷結果列表以使其變平。
mylist = ['Jack 32', 'Perry 12', 'Tim 14']
my_new_list = []
for l in mylist:
my_new_list.extend(l.split())
或者,您可以使用發電機
您應該只能夠讀取為字符串並在空白處分割。
with open('filelocation') as f:
split_up = f.read().split()
嘗試這樣:
my_list = []
with open('your_file') as f:
for x in f:
my_list += x.strip().split()
我認為,如果您獲取列表的內容,則會返回並在空白處進行分割,這將為您提供所需的內容。
可能有一個比這更簡單的方法
In [46]: a=['Jack 32', 'Perry 12', 'Tim 14']
In [47]: b=[i.split() for i in a ]
In [49]: b
Out[49]: [['Jack', '32'], ['Perry', '12'], ['Tim', '14']]
In [50]: [item for sublist in b for item in sublist]
Out[50]: ['Jack', '32', 'Perry', '12', 'Tim', '14']
分割每一行后,可以使用itertools.chain鏈接元素:
from itertools import chain
with open('filepath') as f:
content = list(chain.from_iterable(x.split() for x in f))
print(content)
['Jack', '32', 'Perry', '12', 'Tim', '14']
您不需要調用.readlines
,就可以遍歷文件對象f
。 line.strip("\\n")
只是剝離換行符,您實際上並沒有拆分。 如果調用每行分裂你最終將與像列表的列表[['Jack', '32'], ['Perry', '12'], ['Tim', '14']]
chain.from_iterable
將每個子列表中的元素鏈接到一個列表中。
.readlines
將所有行讀取到內存中,這對於一個小文件來說無關緊要,但是如果您有大文件或受限制的內存,則應避免調用.read
或.readlines
。
為什么不將文件流化為新行之間帶有空格的字符串,然后按空格分開?
無論如何,您要做的只是按空間划分。
我知道這不是“最性感”的答案,但可能是您使用情況最直接的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.