Hello!
I am a beginner at python and I have a question regarding nested lists and how to separete them.
Let's say I have a txt-file that looks like this:
------------------------------
one 1
2 3 hi hello
2 3 hi
-----------------------------
two 2
2 3 hi
2 3 hi bye bye
------------------------------
Then I have managed on my own to create a big list with smaller lists:
Big_list = [[----------]['one', 1],[2,3,'hi','hello'],[2,3,'hi'],[----------]['two', 2],[2,3,'hi'],[2,3,'hi','bye','bye]
Now I have a question regarding how to get the result like this:
Big_list = [[['one', 1],2,3,'hi','hello'],[['one', 1],2,3,'hi'],[['two', 2],2,3,'hi'],[['two', 2]2,3,'hi','bye','bye]]]
I have tried to do this:
for lists in big_list:
for index in lists:
if len(lists) == 1:
break
else:
if lists [0][0] == str:
save = []
save.append(lists[0]
del(lists[0])
break
else:
separated_schedule.append(lists)
break
If the length is one for the list containing: '-------' it should skip that list.
Then, if the first character in one of the small lists is a str I want to separate/ take out that entire list and save it separately.
Then I want to remove that small list from the big list.
I want to add the saved list in the beginning of each of the lists in the "corresponding rows" and maybe save those in a new list?
This is where I get stuck!
CodePudding user response:
If you already have Big_list
consisting of smaller lists you can do:
Big_list = [
["----------"],
["one", 1],
[2, 3, "hi", "hello"],
[2, 3, "hi"],
["----------"],
["two", 2],
[2, 3, "hi"],
[2, 3, "hi", "bye", "bye"],
]
out, flag, current = [], False, None
for l in Big_list:
if len(l) == 1 and "---" in l[0]:
flag = True
elif flag:
current = l
flag = False
else:
out.append([current, *l])
print(out)
this prints:
[
[["one", 1], 2, 3, "hi", "hello"],
[["one", 1], 2, 3, "hi"],
[["two", 2], 2, 3, "hi"],
[["two", 2], 2, 3, "hi", "bye", "bye"],
]
Edit: Updated the answer with new input.