如何在不创建新列表的情况下将此列表拆分为同一个列表
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!']
也许你可以试试 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)
输出:
['charmander', '4/16/2022 18:5:52', '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!', '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!']
也许你可以试试 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)
输出:
['charmander', '4/16/2022 18:5:52', 'Good to see you!' , 'charmander', '4/16/2022 18:5:52', 'Good to see you!']