Friday 11 December 2020

list operations in python

  1. How to make each term of an array repeat, with the same terms grouped together?
    i/p:[A,B,C]
    o/p:[A,A,A,B,B,B,C,C,C]

    Solution:
    >>> l=['A','B','C']
    >>> [x for x in l for _ in range(3) ]
    ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']

    [or]
    >>> import numpy as np
    >>> l=['A','B','C']
    >>> np.repeat(l,3).tolist()
    ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
    [or]

    >>> list(chain(*zip(*[l]*3)))
    ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
     



  2. adding 1 constant value to all sub_list in a list in python
    >>> l=[[1,2],[3,4],[5,6]]
    Add one more element('one') to the sublist
    Solution:
    >>> l=[[1,2],[3,4],[5,6]]
    >>> [x+['one'] for x in l]
    [[1, 2, 'one'], [3, 4, 'one'], [5, 6, 'one']]
  3. How do I remove all "nan" from the following list?
    mylist = [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, n nan, 340000.0, 340050.0, 338003.0, 338004.0, 338005.0, 338006.0, 338008.0, 338010.0, 338011.0, 338018.0, 338019.0, nan, nan, nan, nan]
    Solution:
    
    mylist.remove(x) is a inplace operation and does return None always
    Instead you should be filtering it as follows
    >>> [x for x in mylist if not math.isnan(x)] [340000.0, 340050.0, 338003.0, 338004.0, 338005.0, 338006.0, 3380

No comments:

Post a Comment

list operations in python

How to make each term of an array repeat, with the same terms grouped together? i/p: [A,B,C] o/p: [A,A,A,B,B,B,C,C,C] Solution: >...