Combine lists by joining strings with matching index values

后端 未结 5 1768
闹比i
闹比i 2021-01-06 11:50

I have two lists that I would like to combine, but instead of increasing the number of items in the list, I\'d actually like to join the items that have a matching index. Fo

5条回答
  •  渐次进展
    2021-01-06 11:56

    As can be seen from the many other answers, there are multiple ways to solve this in python. Here's one such example:

    >>> from operator import add
    >>> List1 = ['A', 'B', 'C']
    >>> List2 = ['1', '2', '3']
    >>> map(add, List1, List2)
    ['A1', 'B2', 'C3']
    

    What you're essentially looking for though, is zipWith, I link to hoogle only because it is easily explainable, and there's no standard implementation of zipWith in python. What it is saying is you supply zipWith a binary function, e.g. operator.add, and two lists, and it returns the lists zip'd together with the function applied to each pair.

    You can abstract this idea out to operate on more than just two lists with a binary operator.

    >>> def zipWith(f, *iterables):
    ...     return map(f, *iterables)
    

    Aside: This may seem like it's not doing much, but it is providing semantics about what is happening. It is zipping the iterables with the function. This is more readable than just using the map version.

    Then you can use it with any function so long as you match the number of input lists to the arity of the function f. For example:

    >>> zipWith(lambda a, b, c: a + b * c, [1, 2, 3], [1, 2, 3], [1, 2, 3])
    [2, 6, 12]
    >>> zipWith(lambda a, b, c: (a + b) * c, List1, List2, [1, 2, 3])
    ['A1', 'B2B2', 'C3C3C3']
    >>> zipWith(lambda a, b: a + b, List1, List2)
    ['A1', 'B2', 'C3']
    >>> zipWith(add, List1, List2)
    ['A1', 'B2', 'C3']
    

提交回复
热议问题