簡體   English   中英

如何在不創建新列表的情況下將此列表拆分為同一個列表

[英]how to i split this list into the same list without creating new list

我如何拆分此列表

['charmander|4/16/2022 18:5:52|Good to see you!', 'charmander|4/16/2022 18:6:0|Good to see you!']

['charmander', '4/16/2022 18:5:52', 'Good to see you!' , 'charmander', '4/16/2022 18:5:52', 'Good to see you!']

順便說一下,這個列表是一個 txt 文件的一部分,並且已經通過這樣做被拆分了

file = open('messages/' + username + '.txt', 'r')

data = file.read().strip()

results = data.split("\n")

您可以使用 string.split("|") 這樣做

l = ['charmander|4/16/2022 18:5:52|Good to see you!', 'charmander|4/16/2022 18:6:0|Good to see you!']
newList = []
for val in l:
    newList += (val.split("|"))

Output:
['charmander',
 '4/16/2022 18:5:52',
 'Good to see you!',
 'charmander',
 '4/16/2022 18:6:0',
 'Good to see you!']

也許您可以嘗試列表理解

with open(f'messages/{username}.txt', 'r') as file:
    data = file.read().strip()
results = [s.split('|') for s in data.split('\n')]
print(results)

Output:

['charmander', '4/16/2022 18:5:52', 'Good to see you!' , 'charmander', '4/16/2022 18:5:52', 'Good to see you!']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM