How to break sublist to make each element in the sub list a normal element in the list in python -
for example have
[[1,2,3],[1,2,3],3,5,6]
i want turn
[1,2,3,1,2,3,3,5,6]
what code in python 3?
iterate a
items, iterate subitems if item list; other append new list:
a = [[1,2,3],[1,2,3],3,5,6] b = [] x in a: if isinstance(x, list): b.extend(x) else: b.append(x) # b == [1,2,3,1,2,3,3,5,6]
another approach using list comprehension (nested for
) combined conditional expression:
>>> = [[1,2,3],[1,2,3],3,5,6] >>> [y x in y in (x if isinstance(x, list) else [x])] [1, 2, 3, 1, 2, 3, 3, 5, 6]
Comments
Post a Comment