Is there a way to combine a list like this? - python

assume that a and b are list.
a = [[1], [2]]
b = [[5, 6, 7], [3, 4, 5]]
I want to get a list which is
[[1,5,6,7], [2,3,4,5]]
Is there any way to do that effectively? Either lists or numpy array is OK.

zip is your friend:
>>> a = [[1], [2]]
>>> b = [[5, 6, 7], [3, 4, 5]]
>>> [x+y for x, y in zip(a, b)]
[[1, 5, 6, 7], [2, 3, 4, 5]]
You can also use map; the operator module provides a ready-made definition of lambda x,y: x + y for such uses.
>>> import operator
>>> list(map(operator.add, a, b))

Related

Sum of two nested lists

I have two nested lists:
a = [[1, 1, 1], [1, 1, 1]]
b = [[2, 2, 2], [2, 2, 2]]
I want to make:
c = [[3, 3, 3], [3, 3, 3]]
I have been referencing the zip documentation, and researching other posts, but don't really understand how they work. Any help would be greatly appreciated!
You may use list comprehension with zip() as:
>>> a = [[1, 1, 1], [1, 1, 1]]
>>> b = [[2, 2, 2], [2, 2, 2]]
>>> [[i1+j1 for i1, j1 in zip(i,j)] for i, j in zip(a, b)]
[[3, 3, 3], [3, 3, 3]]
More generic way is to create a function as:
def my_sum(*nested_lists):
return [[sum(items) for items in zip(*zipped_list)] for zipped_list in zip(*nested_lists)]
which can accept any number of list. Sample run:
>>> a = [[1, 1, 1], [1, 1, 1]]
>>> b = [[2, 2, 2], [2, 2, 2]]
>>> c = [[3, 3, 3], [3, 3, 3]]
>>> my_sum(a, b, c)
[[6, 6, 6], [6, 6, 6]]
If you're going to do this a whole bunch, you'll be better off using numpy:
import numpy as np
a = [[1, 1, 1], [1, 1, 1]]
b = [[2, 2, 2], [2, 2, 2]]
aa = np.array(a)
bb = np.array(b)
c = aa + bb
Working with numpy arrays will be much more efficient than repeated uses of zip on lists. On top of that, numpy allows you to work with arrays much more expressively so the resulting code us usually much easier to read.
If you don't want the third party dependency, you'll need to do something a little different:
c = []
for a_sublist, b_sublist in zip(a, b):
c.append([a_sublist_item + b_sublist_item for a_sublist_item, b_sublist_item in zip(a_sublist, b_sublist)])
Hopefully the variable names make it clear enough what it going on here, but basically, each zip takes the inputs and combines them (one element from each input). We need 2 zips here -- the outermost zip pairs lists from a with lists from b whereas the inner zip pairs up individual elements from the sublists that were already paired.
I use python build-in function map() to do this.
If I have simple list a and b, I sum them as this way:
>>> a = [1,1,1]
>>> b = [2,2,2]
>>> map(lambda x, y: x + y, a, b)
[3, 3, 3]
If I have nested list a and b, I sum them as a similar way:
>>> a = [[1, 1, 1], [1, 1, 1]]
>>> b = [[2, 2, 2], [2, 2, 2]]
>>> map(lambda x, y: map(lambda i, j: i + j, x, y), a, b)
[[3, 3, 3], [3, 3, 3]]

sort a matrix using its value in python

For example I have a matrix
a = [[6,8,9],[7,4,3],[1,2,5]]
now I want to sort matrix like as below
a = [[1,2,3],[4,5,6],[7,8,9]]
please help me I am new to python.
For list-of-list, you can clone the shape like this
>>> from itertools import chain
>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> it = iter(sorted(chain.from_iterable(a)))
>>> [[next(it) for j in i] for i in a]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Use chain.from_iterable
>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> from itertools import chain
>>> l = sorted(chain.from_iterable(a))
>>> [l[i:i+3] for i in range(0, len(l),3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

python element wise add in list of list with other list

I checked similar problem at sum of N lists element-wise python
but mine is a little bit more complicate cause I am adding list of list with another list of list
my list looks like it below
[[0 0.014285714 0.035600016]
,[0.014285714 0 0.038359389]
,[0.035600016 0.038359389 0]]
[[0 0.014285714 0.035600016]
,[0.014285714 0 0.038359389]
,[0.035600016 0.038359389 0]]
so adding these two then results has 3 by 3 matrix
how could I efficiently add these two lists?
Can i solve using numpy:
>>> a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b = [[4, 5, 6], [4, 5, 6], [4, 5, 6]]
>>> from numpy import array, sum
>>> list(array(a) + array(b))
[array([5, 7, 9]), array([5, 7, 9]), array([5, 7, 9])]
OR
>>> sum([a, b], axis=0)
array([[5, 7, 9],
[5, 7, 9],
[5, 7, 9]])
>>>
You tagged your question numpy, so I assume this is OK:
import numpy as np
a = np.matrix(a)
b = np.matrix(b)
c = a + b
Where a and b are your two lists, and c is the two added together.
By far the simplest with numpy. :)
If you are working with numpy matrices, #AlexThornton has the best answer
If you are dealing with lists, you should do:
summed_list = [[c+d for c,d in zip(i,j)] for i,j in zip(a,b)] #a,b are your two lists
Simple example:
>>> a = [[1,2,3],[1,2,3],[1,2,3]]
>>> b = [[4,5,6],[4,5,6],[4,5,6]]
>>> summed_list = [[c+d for c,d in zip(i,j)] for i,j in zip(a,b)] #a,b are your two lists
>>> print summed_list
[[5,7,9],
[5,7,9],
[5,7,9]]
Here is a recursive solution using 'vanilla' python and recursion
(This solution works for nested tuples or lists)
from operator import add
def list_recur(l1, l2, op = operator.add):
if not l1:
return type(l1)([])
elif isinstance(l1[0], type(l1)):
return type(l1)([list_recur(l1[0], l2[0], op)]) + \
list_recur(l1[1:],l2[1:], op)
else:
return type(l1)([op(l1[0], l2[0])]) + \
list_recur(l1[1:], l2[1:], op)
This solution takes arguments list1, list2 and optionally the operation you want to perform element-wise (by default addition).
For example, list_recur([ [1, 2, 3, [4, 5] ], [1, 2, 3, [4, 5] ]) will return [ [2, 4, 6, [8, 10] ].
More complex examples will work too:
list_recur([[[[[1,[[[[2, 3]]]]]]]], [[[[3, [[[[4, 1]]]]]]]], lambda x, y: \
x < y) will return [[[[True, [[[[True, False]]]]]]]]
`

Inserting an item after each item in a list (Python)

Say I have a list like this:
a = [[1, 2, 3], [4, 5, 6]]
filler = ['cat']
How could I get
b = [[1 ,2 ,3], ['cat'], [4, 5, 6], ['cat']]
As an output?
I prefer to use itertools for stuff like this:
>>> import itertools as it
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> filler = ['cat']
>>> list(it.chain.from_iterable(it.izip(a, it.repeat(filler))))
[[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
I like the itertools-based solutions posted here, but here's an approach that doesn't require list comprehensions or itertools, and I bet it's super fast.
new_list = [filler] * (len(a) * 2)
new_list[0::2] = a
Here's an idea:
import itertools
a = [[1, 2, 3], [4, 5, 6]]
filler = ['cat']
print list(itertools.chain.from_iterable(zip(a, [filler] * len(a))))
Output:
[[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
Not pythonic but seems to work.
list = [[1, 2, 3], [4, 5, 6]]
result = []
for e in list:
result.append(e)
result.append(['cat'])
result.pop()
Found at this post:
Add an item between each item already in the list
something like this using itertools.islice() and itertools.cycle():
cycle() is used to repeat an item, and used islice() cut the number of repeatation to len(a), and then use izip() or simple zip() over a and the iterator returned by islice() ,
this will return list of tuples.
you can then flatten this using itertools.chain().
In [72]: a
Out[72]: [[1, 2, 3], [4, 5, 6]]
In [73]: b
Out[73]: ['cat']
In [74]: cyc=islice(cycle(b),len(a))
In [75]: lis=[]
In [76]: for x in a:
lis.append(x)
lis.append([next(cyc)])
....:
In [77]: lis
Out[77]: [[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
or:
In [108]: a
Out[108]: [[1, 2, 3], [4, 5, 6]]
In [109]: b
Out[109]: ['cat']
In [110]: cyc=islice(cycle(b),len(a))
In [111]: list(chain(*[(x,[y]) for x,y in izip(a,cyc)]))
Out[111]: [[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
a = [[1, 2, 3], [4, 5, 6]]
filler = ['cat']
out = []
for i in a:
out.append(i)
out.append(filler)
result = [si for i in zip(a, [filler]*len(a)) for si in i]
Try this, as a one-liner:
from operator import add
a = [[1, 2, 3], [4, 5, 6]]
filler = ['cat']
reduce(add, ([x, filler] for x in a))
> [[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
Or even simpler, without using reduce:
sum(([x, filler] for x in a), [])
> [[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]
Both solutions do the same: first, create a generator of [element, filler] and then flatten the resulting stream of pairs. For efficiency, the first step is performed using generators to avoid unnecessary intermediate lists.
UPDATE:
This post is a textbook example of why a troll must not be fed in an online forum. See the comments to see what I mean. It's better to just ignore the troll.
python 3.2
a = [[1, 2, 3], [4, 5, 6]]
b = ['cat']
_=[a.insert(x,b) for x in range(1,len(a)*2,2)]

concatenate lists in python

I have a 3x2 list called x and a 1x2 list called y:
x=[[1,2],[3,4],[5,6]]
and
y=[10,20]
my question is how to concatenate y to the end of x to end up with a 4x2 list like:
x=[[1,2],[3,4],[5,6],[10,20]]
I've tried this:
xx=[x,y]
but it gives me this which is not a 4x2 list:
xx=[[[1,2],[3,4],[5,6]],[10,20]]
>>> x = [[1, 2], [3, 4], [5, 6]]
>>> x
[[1, 2], [3, 4], [5, 6]]
>>> x.append([10, 20])
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]
Or:
>>> x = [[1, 2], [3, 4], [5, 6]]
>>> x
[[1, 2], [3, 4], [5, 6]]
>>> x += [[10, 20]] # a list with a list as its only element
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]
Given:
x = [[1,2],[3,4],[5,6]]
y = [10,20]
this:
x.append(y)
will give you:
[[1, 2], [3, 4], [5, 6], [10, 20]]
Note however that this modifies x.
If you don't want to modify x, this is another way:
xx = x + [y[:]]
setting xx to:
[[1, 2], [3, 4], [5, 6], [10, 20]]
We use y[:] rather than simply y in the above assignment because we want to create separate copy of y for xx so later, should (the original) y be modified it would not lead to changes in xx.
>>> x=[[1,2],[3,4],[5,6]]
>>> y=[10,20]
>>> x.append(y) # or x.append(list(y)) to append a shallow copy of y
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]
If you want a new list:
z = x + [y]
Note, that using [y] makes the content a list within a list, so that this works.
If you want to modify x inplace, then:
x.append(y)
Although I don't use it often myself, I think it's worth mentioning the list's extend member function:
>>> x=[[1,2],[3,4],[5,6]]
>>> y=[10,20]
>>> x.extend([y])
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]
http://docs.python.org/tutorial/datastructures.html#more-on-lists

Categories