brain storm
brain storm

Reputation: 31252

how to get a sublist of desired length using python?

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

Upvotes: 0

Views: 2252

Answers (5)

gaurav
gaurav

Reputation: 91

If you want to do it recursive way

import collections

def doMagic(data):
    if isinstance(data, collections.Iterable):
        if all(type(elem) in [type(1), type('a')] for elem in data):
            return data[:2]
        else:
            return [doMagic(elem) for elem in data][:2]
    else:
        return data

if __name__ == '__main__':
    data = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6,5,4]]]
    print [doMagic(elem) for elem in data]

Upvotes: 0

kiriloff
kiriloff

Reputation: 26333

If you do not want to create a new list, simply do

>>> A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6,5,4]]]
>>> for X in A:
    X[1]=X[1][:2]


>>> A
[['A', [1, 2]], ['D', [3, 4]], ['E', [6, 7]], ['F', [1]], ['G', [7, 6]]]

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

use map on each item of sublist, because 'A'[:2] will return 'A' only.

In [115]: A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6,5,4]]]

In [116]: [map(lambda x:x[:2],x) for x in A]
Out[116]: [['A', [1, 2]], ['D', [3, 4]], ['E', [6, 7]], ['F', [1]], ['G', [7, 6]]]

Upvotes: 0

Elalfer
Elalfer

Reputation: 5338

You can utilize map function

>>> a=[[1,[1,2,3]],[2,[1]],[3,[1,2]]]
>>> map(lambda v: [v[0],v[1][:2]], a)
[[1, [1, 2]], [2, [1]], [3, [1, 2]]]

Upvotes: 1

avasal
avasal

Reputation: 14854

you can make use of list comprehension for this:

In [71]: A = [['A',[1,2,3]],['D',[3,4]],['E',[6,7]],['F',[1]],['G',[7,6,5,4]]]

In [72]: [[x[0],x[1][:2]] for x in A]
Out[72]: [['A', [1, 2]], ['D', [3, 4]], ['E', [6, 7]], ['F', [1]], ['G', [7, 6]]]

Upvotes: 3

Related Questions