Reputation: 1
How do I check the sum of a row without numpy? If I have this code:
Matrix = [["X", "X", "X"],[ "O", "O", "X"], ["X", "O", "X"]]
How do I check the sum of every row in the matrix without numpy?
Example:
In the matrix above my sum would be x = "XXX", "OOX", "XOX"
EDIT
I do not like to use stuff like .join
and .map
.
Upvotes: 0
Views: 7068
Reputation: 429
Your code doesn't create a matrix. It errors out. If you want to represent a matrix with lists, you could do the following:
matrix = [[1,1,1],[2,2,2],[0,0,0]]
You could then find the sum of each row with a list comprehension:
[sum(row) for row in matrix]
EDIT: The question has changed, so for later readers I want to make sure it's clear. sum will add numbers, not concatenate strings. If you want to concatenate strings, your list comprehension should look like this:
[[''.join(row) for row in matrix]]
If you want to assign names to each row, instead of creating a separate variable for each, stick the list of sums into a for loop and assign each sum to a dictionary:
sum_dict = {}
i=0
for s in sum_list:
sum_dict['r'+str(i)] = s
i +=1
Will give you a dictionary with keys r0,r1,r2, etc.
Upvotes: 1
Reputation: 78546
You can use a list comprehension and str.join
:
Matrix = [["X", "X", "X"],[ "O", "O", "X"], ["X", "O", "X"]]
m = [''.join(i) for i in matrix]
print(m)
# ['XXX', 'OOX', 'XOX']
To create a more general solution for adding different types you can use reduce
with operator.add
:
from operator import add
# from functools import reduce # Py3
Matrix = [1, 1, 2], ["O", "O", "X"], ["X", "O", "X"]
m = [reduce(add, i) for i in Matrix]
print(m)
# [4, 'OOX', 'XOX']
Upvotes: 1
Reputation: 1307
You can use join on an empty string:
x = [''.join(row) for row in Matrix]
Upvotes: 0