I want to convert my list of lists and within these lists there are list into only list of lists. For example:
My code:
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
aaa = len(a)
aa = [[] for i in range(aaa)]
for i, x in enumerate(a):
if len(x) != 0:
for xx in x:
for xxx in xx:
aa[i].append(xxx)
print(aa)
Currently:
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
to expected:
[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
My current code works in finding the expected output. However, i have to use too many for loop and its too deep. Is there a shorter way to do so like just in one or 2 lines?
You can do it with list comprehension, just by checking to see whether the nested list is empty or not, and, if not, replacing the outer list with the inner list (by index).
data = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
result = [d[0] if d else d for d in data]
print(result)
# OUTPUT
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With