I want to multiply all the values in a list of lists in python:
input = 3*[[1,2,3],[3,2,1]]
so i get this output:
output = [[3,6,9],[9,6,3]]
i tried this:
l = [[1,2,3],[3,2,1]]
l = [i * 2 for i in x in l]
[[ 3 * i for i in inner ] for inner in outer]
>>> my_list = [[1,2,3],[3,2,1]]
>>> [map((3).__mul__, sublist) for sublist in my_list]
[[3, 6, 9], [9, 6, 3]]
You might consider using numpy arrays instead:
>>> import numpy as np
>>> a = np.array(my_list)
>>> a
array([[1, 2, 3],
[3, 2, 1]])
>>> 3*a
array([[3, 6, 9],
[9, 6, 3]])
Related
I'm very new to python (using python3) and I'm trying to add numbers from one list to another list. The only problem is that the second list is a list of lists. For example:
[[1, 2, 3], [4, 5, 6]]
What I want is to, say, add 1 to each item in the first list and 2 to each item in the second, returning something like this:
[[2, 3, 4], [6, 7, 8]]
I tried this:
original_lst = [[1, 2, 3], [4, 5, 6]]
trasposition_lst = [1, 2]
new_lst = [x+y for x,y in zip(original_lst, transposition_ls)]
print(new_lst)
When I do this, I get an error
can only concatenate list (not "int") to list
This leads me to believe that I can't operate in this way on the lists as long as they are nested within another list. I want to do this operation without flattening the nested list. Is there a solution?
One approach using enumerate
Demo:
l = [[1, 2, 3], [4, 5, 6]]
print( [[j+i for j in v] for i,v in enumerate(l, 1)] )
Output:
[[2, 3, 4], [6, 7, 8]]
You can use enumerate:
l = [[1, 2, 3], [4, 5, 6]]
new_l = [[c+i for c in a] for i, a in enumerate(l, 1)]
Output:
[[2, 3, 4], [6, 7, 8]]
Why don't use numpy instead?
import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6]])
mul = np.array([1,2])
m = np.ones(mat.shape)
res = (m.T *mul).T + mat
You were very close with you original method. Just fell one step short.
Small addition
original_lst = [[1, 2, 3], [4, 5, 6]]
transposition_lst = [1, 2]
new_lst = [[xx + y for xx in x] for x, y in zip(original_lst, transposition_lst)]
print(new_lst)
Output
[[2, 3, 4], [6, 7, 8]]
Reasoning
If you print your original zip it is easy to see the issue. Your original zip yielded this:
In:
original_lst = [[1, 2, 3], [4, 5, 6]]
transposition_lst = [1, 2]
for x,y in zip(original_lst, transposition_lst):
print(x, y)
Output
[1, 2, 3] 1
[4, 5, 6] 2
Now it is easy to see that you are trying to add an integer to a list (hence the error). Which python doesn't understand. if they were both integers it would add them or if they were both lists it would combine them.
To fix this you need to do one extra step with your code to add the integer to each value in the list. Hence the addition of the extra list comprehension in the solution above.
A different approach than numpy that could work even for lists of different lengths is
lst = [[1, 2, 3], [4, 5, 6, 7]]
c = [1, 2]
res = [[l + c[i] for l in lst[i]] for i in range(len(c))]
INPUT:
M = [[1,2,3],
[1,2,3],
[1,2,3]]
how take the sum of the columns in the two first rows and implement it in the array M
OUTPUT:
M = [[2,4,6],
[1,2,3]]
Use numpy.add.reduceat:
import numpy as np
M = [[1,2,3],
[1,2,3],
[1,2,3]]
np.add.reduceat(M, [0, 2])
# indices [0,2] splits the list into [0,1] and [2] to add them separately,
# you can see help(np.add.reduceat) for more
# array([[2, 4, 6],
# [1, 2, 3]])
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
M[:2] = [[a + b for a, b in zip(M[0], M[1])]]
print(M) # [[5, 7, 9], [7, 8, 9]]
Things to google to understand this:
M[:2] =: python slice assignment
[... for .. in ...]: python list comprehension
for a, b in ...: python tuple unpacking loop
I need to separate 2D array in order to have last column and the rest separately. Those must be arrays both.
Does this help?
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> l = [row[:-1] for row in a]
>>> r = [row[-1] for row in a]
>>> l
[[1, 2], [4, 5], [7, 8]]
>>> r
[3, 6, 9]
I have a matrix like this
[[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
how i get the partial sums by columns in python?
[[1,2,4,6],
[(4-1),(7-2),(9-4),(9-6)],
[(1-4),(9-7),(10-9),(20-9)]]
If you want a solution that doesn't involve numpy, and just uses list of lists and itertools.tee (which is builtin), then the below should work
from itertools import tee
a = [[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
b = []
b.append(a[0])
# Create two iterators and advance one once.
x, y = tee(a)
next(y)
# Iterate over your two iterators and construct a list t which is their difference
# then append this list to b
for i, j in zip(x, y):
t = [h-g for g, h in zip(i,j)]
b.append(t)
print(b)
# [[1, 2, 4, 6],
# [3, 5, 5, 3],
# [-3, 2, 1, 11]]
Try
np.vstack((Z[0],np.diff(Z,axis=0)))
where Z is the matrix you are differentiating.
From the second line, what you want is just the difference of row i and row i-1, and the first line is just the first line of the original array. The easiest way to get this is with numpy. So this works:
In [1]: import numpy as np
In [2]: a = np.array( [[1,2,4,6],
...: [4,7,9,9],
...: [1,9,10,20]]
...: )
In [3]: np.vstack( (a[0], a[1:]-a[:-1]) )
Out[3]:
array([[ 1, 2, 4, 6],
[ 3, 5, 5, 3],
[-3, 2, 1, 11]])
As Lord Henry Wotton (!) points out, the difference a[1:]-a[:-1] is the same as np.diff(a, axis=0).
If you don't want to use numpy or itertools, here is the code
>>> a=[[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> a_r = a[::-1] # reverse original list
>>> for i in range(len(a_r)-1):
... for j in range(len(a_r[0])):
... a_r[i][j] = a_r[i][j] - a_r[i+1][j]
...
>>> a=a_r[::-1] # reverse result
>>> for i in a: print i
[1, 2, 4, 6]
[3, 5, 5, 3]
[-3, 2, 1, 11]
I think this one is nice
>>> a = [[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> c = [[0]*5] ; c.extend(a)
>>> print [[ s-r for r, s in zip(*t)] for t in zip(c[:-1],c[1:])]
[[1, 2, 4, 6], [3, 5, 5, 3], [-3, 2, 1, 11]]
>>>
Here I prepend a list of zeros to the list of lists (obtaining c), and by a bit of packing and unpacking using zip I have a list of lists with the expected results.
Suppose I have a python list l=[1,2,3,4,5]. I would like to find all x-element lists starting with elements that satisfy a function f(e), or the sublist going to the end of l if there aren't enough items. For instance, suppose f(e) is e%2==0, and x=3 I'd like to get [[2,3,4],[4,5]].
Is there an elegant or "pythonic" way to do this?
>>> f = lambda e: e % 2 == 0
>>> x = 3
>>> l = [1, 2, 3, 4, 5]
>>> def makeSublists(lst, length, f):
for i in range(len(lst)):
if f(lst[i]):
yield lst[i:i+length]
>>> list(makeSublists(l, x, f))
[[2, 3, 4], [4, 5]]
>>> list(makeSublists(list(range(10)), 5, f))
[[0, 1, 2, 3, 4], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8], [6, 7, 8, 9], [8, 9]]
Using a list comprehension:
>>> l = range(1,6)
>>> x = 3
>>> def f(e):
return e%2 == 0
>>> [l[i:i+x] for i, j in enumerate(l) if f(j)]
[[2, 3, 4], [4, 5]]