In DrRacket, is there any way I can change (list 1 (list 2 (list 3 4 5) 6 )7) to (list 1 2 3 4 5 6 7)?
Solution to given question:
Yes, there are multiple ways to convert any nested list to normal form
Three possible ways mnetioned here:
=======================================
1) Code
import collections
from itertools import chain
#input list called L
L = [1,2,[3,4,5],6,7]
#if an item in the list is not already a list, then put it in one.
a = [i if isinstance(i, collections.Iterable) else [i,] for i in L]
#flattens out a list of iterators
b = list(chain.from_iterable(a))
print b
#[1, 2, 3, 4, 5, 6, 7]
===============================================================
2)
L = [1,2,[3,4,5],6,7]
new_list = []
[new_list.extend(x) if type(x) is list else new_list.append(x) for x in L]
print new_list
(or)
3)
new_list2 = []
for item in L:
if type(item) is list:
new_list2.extend(item)
else:
new_list2.append(item)
print new_list2
Get Answers For Free
Most questions answered within 1 hours.