given a list with sublists, I want to extract the sublists with specified length.
If the sublist has length less than the specified, then extract all. Kindly see below for clarification
In the below example, I am extracting for sublists with length = 2. If length is greater, I extract the first two elements in sublist and ignore the remaining.
Input
A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6,5,4]]]
Output
B = [['A',[1,2]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6]]]
I am currently doing as follows, it works, but wondering if there is a simple way
B=[]
for el in A:
l = []
if len(el[1]) > 2:
l.append(el[0])
l.append(el[1][0:2])
B.append(l)
else:
l.append(el[0])
l.append(el[1][0:2])
B.append(l)
print B
you can make use of list comprehension for this: