Creating a matrix with a generator

I have a list:

l = [1,2,3]

I need my conclusion:

m = [(1-1, 1-2, 1-3),(2-1, 2-2, 2-3), (3-1, 3-2, 3-3)]
m = [[0, -1, -2], [1,0,-1], [-2,-1,0]]

I wrote this function and it works great:

def matrixer(l):
    matrix = []

    for data in l:
        column = []
        column.append(data - l[0])
        column.append(data - l[1])
        column.append(data - l[2])
        matrix.append(column)

    return matrix

But this does not scale very well, since my list can have up to 100 values, and I do not want to add the following line of code for each value in my list:

column.append(data - l[n])

I have not used generators before, but it looks like the solution will include one. I have always tried the while loop, but it doesn’t quite suit me when I encounter the same problem.

+4
source share
4 answers

Using two for loops, we must reset sub_answereach time. It looks dirty, so maybe another option; can be found below:

l = [1,2,3]
answer = []
for each in l:
  sub_answer = []
  for every in l:
    sub_answer.append(each-every)
  answer.append(sub_answer)
  sub_answer = []
print(answer)
#[[0, -1, -2], [1, 0, -1], [2, 1, 0]]

for . sub_answer:

l = [1,2,3]
answer = []
for each in l:
  answer.append([each-x for x in l])
print(answer)
#[[0, -1, -2], [1, 0, -1], [2, 1, 0]]

l . , , , , each, .

l l = [1,2,3,4,5,6,7], :

[[0, -1, -2, -3, -4, -5, -6], [1, 0, -1, -2, -3, -4, -5], [2, 1, 0, -1, -2, -3, -4], [3, 2, 1, 0, -1, -2, -3], [4, 3, 2, 1, 0, -1, -2], [5, 4, 3, 2, 1, 0, -1], [6, 5, 4, 3, 2, 1, 0]]

(3-1 is not -2... it 2....)


, ?!?!?!: for :

l = [1,2,3]
print([[each-x for x in l] for each in l])
#[[0, -1, -2], [1, 0, -1], [2, 1, 0]]

, , , .

+4

:

def matrixer(l):
    return [[e - d for d in l] for e in l]
  • listcomp
  • listcomp

:

[[0, -1, -2], [1, 0, -1], [2, 1, 0]]

( ) ( ), + , , .

+2

Short answer (the shortest so far ^^):

l = [1, 2, 3]

m = [[row - col for row in l] for col in l]

This uses list comprehension .

+2
source

You can use list comprehensionwith map()and operatoras follows:

[map(operator.sub, [item]*len(l), l) for item in l]

This is equivalent to:

matrix = []

for item in l:
    matrix.append(map(operator.sub, [item]*len(l), l))

Explanation:

For each itemin, lwe create a list [item]*len(l), and we use map()and operatorto get the subtraction of these two lists. For the first element of l, equal to 1, we have:

[1]*3  # => [1, 1, 1]

Then:

map(operator.sub, [1, 1, 1], [1, 2, 3])  # [1-1, 1-2, 1-3] => [0, -1, -2]

Conclusion:

>>> import operator
>>>
>>> l = [1, 2, 3]
>>> [map(operator.sub, [item]*len(l), l) for item in l]
[[0, -1, -2], [1, 0, -1], [2, 1, 0]]
+1
source

Source: https://habr.com/ru/post/1663276/