简体   繁体   中英

Python - Adding each element of 2 lists in different length

The following code can add each element of 2 lists in the same length, however, I want it to add up each list in different length, for example add up list1 = [1, 2] and list2 = [1, 2, 3].

2ndly, In the 5th line, if I change the code to new_list = [list1[num] + list2[num]] , it will only sum up the total, without adding up each element, I wonder why?

def add_lists_V2(list1, list2):
    new_list = []
    max_list = max(list1, list2)
    for num in range(len(max_list)):
        new_list = new_list + [list1[num] + list2[num]]

    return new_list

def input_integer_list():
    nums = input("Enter integers: ")
    num_list = nums.split()
    for i in range(len(num_list)):
        num_list[i] = int(num_list[i])
    return num_list

def main():
    print("Add two lists of any size.")
    list1 = input_integer_list()
    list2 = input_integer_list()
    new_list = add_lists_V2(list1, list2)
    print("Sum of two lists:", new_list)

main()

The itertools module is your friend. Specifically, zip_longest , though depending on what your end goal is there might be more there that can help you.

>>> import itertools
>>>
>>> l1 = range(2)
>>> l2 = range(3)
>>>
>>> map(sum, itertools.zip_longest(l1, l2, fillvalue=0))
[0, 2, 2]

I am proposing one solution below but I know it's not the best. Hopefully, someone can avoid the messy if-else and give a more elegant solution.

Firstly, reading and processing input can be simplified. Method map() is useful for operations on each element of the list. Likewise, map() in conjunction with operator.add can be used to add up element-wise multiple lists. To handle lists of different sizes, use pythonic way of making sub-lists.

from operator import add

def add_lists_V2(list1, list2):
    if len(list1) > len(list2):
        m = len(list2)
        r = list1[m:]
    else:
        m = len(list1)
        r = list2[m:]
    return map(add, list1[:m], list2[:m]) + r

def input_integer_list():
    nums = input("Enter integers: ")
    return map(int,nums.split())

def main():
    print("Add two lists of any size.")
    list1 = input_integer_list()
    list2 = input_integer_list()
    new_list = add_lists_V2(list1, list2)
    print("Sum of two lists:", new_list)

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM