Python) I Wanna Add Two Lists Which Are Different Order of Len

Python) I wanna add two lists which are different order of len

You can use izip_longest from itertools

Ex:

from itertools import izip_longest
list1=[1,2,3,4,5]
list2=[1,1,1,1,1,1,1]
print([sum(i) for i in izip_longest(list1, list2, fillvalue=0)])

Output:

[2, 3, 4, 5, 6, 1, 1]

Add two lists of different lengths in python, start from the right

Edit (2020-18-03):

>>> P = [3, 0, 2, 1]
>>> Q = [8, 7]
>>> from itertools import zip_longest
>>> [x+y for x,y in zip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]
[3, 0, 10, 8]

Obviously, if you choose a convention where the coefficients are ordered the opposite way, you can just use

P = [1, 2, 0, 3]
Q = [7, 8]
[x+y for x,y in zip_longest(P, Q, fillvalue=0)]

Combine two lists of different length python

The code below should achieve what you need

import itertools
import operator

l1 = [1, 2, 3]
l2 = [1, 2, 3, 4]

list(itertools.starmap(operator.mul, itertools.zip_longest(l1, l2, fillvalue=1)))
# result [1, 3, 9, 4]

Explanation

zip_longest will zip and fill missing values from shorter list:

itertools.zip_longest(l1, l2, fillvalue=1)
[(1, 1), (2, 2), (3, 3), (1, 4)]

starmap will apply multiplication operator to every integer pair

python compare items in 2 list of different length - order is important

Use the zip() function to pair up the lists, counting all the differences, then add the difference in length.

zip() will only iterate over the items that can be paired up, but there is little point in iterating over the remainder; you know those are all to be counted as different:

differences = sum(a != b for a, b in zip(list_1, list_2))
differences += abs(len(list_1) - len(list_2))

The sum() sums up True and False values; this works because Python's boolean type is a subclass of int and False equals 0, True equals 1. Thus, for each differing pair of elements, the True values produced by the != tests add up as 1s.

Demo:

>>> list_1 = ['a', 'a', 'a', 'b']
>>> list_2 = ['a', 'b', 'b', 'b', 'c']
>>> sum(a != b for a, b in zip(list_1, list_2))
2
>>> abs(len(list_1) - len(list_2))
1
>>> difference = sum(a != b for a, b in zip(list_1, list_2))
>>> difference += abs(len(list_1) - len(list_2))
>>> difference
3

Combine data from multiple lists of different length

First, key a dict off of the first two elements, using zeros as default for month and week. Then fill in the month and week, if necessary:

data = {(name, n): [y, 0, 0] for name, n, y in year}

for name, n, m in month:
data[name, n][1] = m

for name, n, w in week:
data[name, n][2] = w

data = tuple(tuple([*k, *v]) for k, v in data.items())


Related Topics



Leave a reply



Submit