我在数据文件中拆分文本时遇到问题,假设数据文件包括:
Row 1
apple
bob
cat
dog
ear
fun
Row 2
glow
horse
idea
joke
kick
lemon
Row 3
money
new
odd
park
queen
run
我想拆分它,使它成为一个嵌套列表,如下所示:
[[apple, bob], [cat, dog], [ear, fun]],
[[glow, horse], [idea, joke], [kick, lemon]],
[[money, new], [odd, park], [queen, run]]
这是我到目前为止的工作:
def text_file(data_file):
nested_list = []
main_list = []
my_list = ''
for index in data_file:
index = index.strip()
if (index in my_list):
main_list.append(nested_list)
nested_list = []
else:
nested_list.append(index)
if (nested_list):
main_list.append(nested_list)
return (main_list)
但这会返回:
text_file(open("data_file.txt", "r"))
[['Row 1', 'apple', 'bob', 'cat', 'dog', 'ear', 'fun'],
['Row 2', 'glow', 'horse', 'idea', 'joke', 'kick', 'lemon'],
['Row 3', 'money', 'new', 'odd', 'park', 'queen', 'run']]
不导入任何东西,我怎么能做到这一点?如果可能的话,我可以在我的代码中添加什么?