merge two lists python - python

I have two lists:
a = [(1,2,3),(4,5,6)]
b = [7,8]
I want to merge it into:
c = [(1,2,3,7),(4,5,6,8)]
I used zip(a,b) but the result does not seem correct. Can anyone help?

zip() will just pair up the tuples and the integers. You also need to concatenate the tuple and the new item:
c = [aa + (bb,)
for aa, bb in zip(a, b)]

>>> a = [(1,2,3),(4,5,6)]
>>> b = [7,8]
>>> c = zip(*a)+[b] #c looks like [(1,4),(2,5),(3,6),(7,8)]
>>> print zip(*c) #zip it back together
[(1, 2, 3, 7), (4, 5, 6, 8)]
>>>

Try
map ( lambda x: x[0]+(x[1],), zip(a,b))

And yet another version:
from itertools import izip
[x+(y,) for x,y in izip(a,b)]
Should be efficient and it expresses what you are really doing in a readable way.

And yet another:
map(lambda t, e: t + (e,), a, b)
No need to zip and unpack; map can take both lists at once.

print((a[0]+(b[0],),a[1]+(b[1],)))

This seems clear to me:
[x + (b[i],) for i,x in enumerate(a)]

Related

How to create a new list by pairing the elements on the basis of index from 2 different lists in Python?

Example, I have the following lists in Python
A = [1,2,3]
B = [4,5,6]
I would need to create a new list C such that the elements should be paired as a separate lists based on their index numbers. i.e., C = [[[1,4],[2,5],[3,6]], [[1,4],[2,5],[3,6]]]
I have written a code to that but it is purely structured. Can you please provide if there is any better way other than the below code?
A = [1,2,3]
B = [4,5,6]
D = [a,b,c]
E = [d,e,f]
C = []
list = []
for i in range(len(A)):
list.append([A[i],B[i]])
C.append(list)
list = []
for i in range(len(D)):
list.append([D[i],E[i]])
C.append(list)
I have to repeat this code if I have multiple cases similar to the above one in my code. Which is poor in structuring.
Can someone suggest any better method for the problem?
You can use zip, convert that to list
list(zip(a,b))
which will give list of tuples. If you want list of lists, you can go:
[[i,j] for i,j in zip(a,b)]
You can try something like this in one line.
C = [[A[i],B[i]] for i in range(len(A))]
Be careful if A and B don't have the same length though!
Your problem has a simple solution found in Python's built-in functions,
The 'zip' function takes 2 arguments (iterables) and return a single iterator.
Here is an example code:
a = [1, 2, 3]
b = [4, 5, 6]
c = list(zip(a, b))
# c -> [(1, 4), (2, 5), (3, 6)]
# if you want the elements to be list instead of tuple you can do
c = [[i, j] for i,j in zip(a, b)]
# c -> [[1, 4], [2, 5], [3, 6]]
you can use zip for this
c= zip(a,b)
c=list(c)
if you convert in set then
c=set(c)
Using numpy, the following would be efficient.
import numpy as np
A = [1,2,3]
B = [4,5,6]
a = np.array(A)
b = np.array(B)
c = np.vstack((a, b)).T
print c
C = c.tolist()
print C
lower case letters are all numpy arrays, upper case are python arrays

Combining map with zip through lambda

I'm trying to write a function for adding 2D vectors.
I'm trying to combine the map() function, getting a list using the zip() function (which will zip 2 tuples).
This is the code:
a = (1, 2)
b = (3, 4)
c = list(map(lambda x, y: x+y, list(zip(a, b))))
print(c)
So the way I see it, zip(a, b) returns a zip object containing the following tuples: (1, 3), (2, 4). It is then converted to a list. I'm getting the following error:
TypeError: () missing 1 required positional argument: 'y'
So my guess is that the lambda function is not taking the second number in each tuple.
Is there any way to do this?
Only one parameter for lambda like:
c = list(map(lambda x: sum(x), zip(a, b)))
But once we are using sum, we can map it directly like:
c = list(map(sum, zip(a, b)))
Test Code:
a = (1, 2)
b = (3, 4)
c = list(map(sum, zip(a, b)))
print(c)
Result:
[4, 6]
In Python2, you can use specific unpacking syntax in a lambda:
a = (1, 2)
b = (3, 4)
c = list(map(lambda (x, y): x+y, list(zip(a, b))))
However, in Python3, you will have to use sum:
c = list(map(lambda x_y: sum(x_y), list(zip(a, b))))
zip returns a tuples, so you could sum like this example:
list(map(lambda x: x[0] + x[1], zip(a, b)))
output:
[4, 6]
The lambda receives one parameter, which is a 2-tuple returned by zip.
You can access it element-wise: lambda pair: pair[0] + pair[1].
You can apply sum() to it.
In Python 2, you can unpack it right in the signature: lambda (x, y): x + y.

Python set/tuple operations iteration

I have a set of tuple(a, b, c). How can I return a list of all a inside this set? Is there something like .keys() as dictionaries have?
myList = [tup[0] for tup in mySet]
They're not "keys" per se.
Use a list comprehension:
data = set([(1, 2, 3), (4, 5, 6)])
all_a = [a for a, b, c in data]
Or if the tuples can be of varying length:
all_a = [t[0] for t in data]

Simpler/preferred way to iterate over two equal-length lists and append the max of each pair to a new list?

Given two lists of equal length, is there a simpler or preferred way to iterate over two lists of equal length and append the maximum of each pair of elements to a new list? These are the two methods I know of.
import itertools
a = [1,2,3,4,5]
b = [1,1,6,3,8]
m1 = list()
m2 = list()
for x, y in zip(a, b):
m1.append(max(x, y))
for x in itertools.imap(max, a, b):
m2.append(x)
Both of these result in [1, 2, 6, 4, 8], which is correct. Is there a better way?
map(max, a, b)
[max(x, y) for x, y in zip(a, b)]
You could do it like:
a = [1,2,3,4,5]
b = [1,1,6,3,8]
m3 = [max(x,y) for (x,y) in zip(a,b)]
or even
m4 = map(max, zip(a,b))
In Python3, map() no longer returns a list, so you should use the list comprehension or
list(map(max, a, b))
if you really need a list and not just an iterator

Finding the sum of matching components in two lists

I have two lists:
A = [1, 2, 3, 4, 5]
B = [6, 7, 8, 9, 10]
And I need to be able to find the sum of the nth terms from both lists i.e. 1+6, 2+7, 3+8 etc
Could someone please tell me how to refer to items in both lists at the same time?
I read somewhere that I could do Sum = a[i] + b[i] but I'm not convinced on how that would work.
>>> import operator
>>> map(operator.add, A, B)
[7, 9, 11, 13, 15]
just to demonstrate Pythons elegance :-)
Use a list comprehension and zip:
[a + b for (a,b) in zip(A,B)]
Are these questions homework? Or self-study?
If you know the lists will be the same length, you could do this:
AB = [A[i] + B[i] for i in range(len(A))]
In Python 2, you might want to use xrange instead of range if your lists are quite large. I think that's an explicit, simple, readable, obvious way to do it, but some might differ.
If the lists might be different lengths, you have to decide how you want to handle the extra elements. Let's say you want to ignore the extra elements of whichever list is longer. Here are three ways to do it:
AB = [A[i] + B[i] for i in range(min(len(A), len(B)))]
AB = map(sum, zip(A, B))
AB = [a + b for a, b in zip(A, B)]
The downside of using zip is that it will allocate a list of tuples, which can be a lot of memory if your lists are already large. Using for i in xrange with subscripting won't allocate all that memory, or you can use itertools.izip:
import itertools
AB = map(sum, itertools.izip(A, B))
If you instead want to pretend the shorter list is padded with zeros, using itertools.izip_longest is the shortest answer:
import itertools
AB = map(sum, itertools.izip_longest(A, B, fillvalue=0))
or
import itertools
AB = [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)]
Although Jazz's solution works for 2 lists, what if you have more than 2 lists? Here's a solution:
def apply_elementwise_function(elements_in_iterables, function):
elementwise_function = lambda x, y: itertools.imap(function, itertools.izip(x, y))
return reduce(elementwise_function, elements_in_iterables)
a = b = c = [1, 2, 3]
>>> list(apply_elementwise_function([a, b, c], sum))
[3, 6, 9]
Hi You can try this too:
>>>a=[1,2,3,4,5]
>>>b=[6,7,8,9,10]
>>>c=[]
>>>for i in range(0,5):
c.append(a[i]+b[i])
>>> c
[7, 9, 11, 13, 15]

Categories