Home > database >  How to append item to match the length of two list in python
How to append item to match the length of two list in python

Time:08-21

I am working on a python script which is connected to a server. Every x min, server returns two list but the length of these list is not same. For ex:

a = [8, 10, 1, 34]
b = [4, 6, 8]

As you can see above that a is of length 4 and b is of length 3. Simillarly sometime it returns

a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]

I have to write a logic where I have to check if length of these two list is not same, then add the 0 at the end of the list which is smaller than other list. So for ex, if input is:

a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]

then output will be:

a = [3, 6, 4, 5, 0, 0]
b = [8, 3, 5, 2, 9, 3]

Can anyone please help me with these. Thanks

CodePudding user response:

def pad(list1, list2):
    # make copies of the existing lists so that original lists remain intact
    list1_copy = list1.copy()
    list2_copy = list2.copy()

    len_list1 = len(list1_copy)
    len_list2 = len(list2_copy)
    # find the difference in the element count between the two lists
    diff = abs(len_list1 - len_list2)
    
    # add `diff` number of elements to the end of the list
    if len_list1 < len_list2:
        list1_copy  = [0] * diff
    elif len_list1 > len_list2:
        list2_copy  = [0] * diff

    return list1_copy, list2_copy


a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
# prints: ([3, 6, 4, 5, 0, 0], [8, 3, 5, 2, 9, 3])
print(pad(a, b))

a = [8, 10, 1, 34]
b = [4, 6, 8]
# prints: ([8, 10, 1, 34], [4, 6, 8, 0])
print(pad(a, b))

CodePudding user response:

For now, I can suggest this solution:

a = [3, 6, 4, 5] 
b = [8, 3, 5, 2, 9, 3]

# Gets the size of a and b.
sizeA, sizeB = len(a), len(b)

# Constructs the zeros...
zeros = [0 for _ in range(abs(sizeA-sizeB))] 

# Determines whether a or b needs to be appended with 0,0,0,0...
if sizeA < sizeB: 
    a  = zeros
else: 
    b  = zeros

print(a,b)

CodePudding user response:

You could also try to use more_itertools padded() method: It's prob. more elegant and adaptable for future Use cases.

Notes: just need to do pip install more_itertools first.


# simple example to demo it:
from more_itertools import padded

print(list(padded([1, 2, 3], 0, 5)))    # last num: 5 is the diff between 2 lists.   

# [1, 2, 3, 0, 0]


  [1]: https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.padded
  • Related