简体   繁体   English

如何在不创建新列表的情况下将此列表拆分为同一个列表

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

how do I split this list我如何拆分此列表

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

to

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

by the way, this list is part of a txt file and has been split already by doing this顺便说一下,这个列表是一个 txt 文件的一部分,并且已经通过这样做被拆分了

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

data = file.read().strip()

results = data.split("\n")

You can do it like this using string.split("|")您可以使用 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!']

Maybe you could try a list-comprehension :也许您可以尝试列表理解

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: 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