1

I have this code that adds the sum of rows in a matrix:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer = str([sum(row) for row in matrix])
print answer

But answer is a string that looks like [3, 5, 1].

How can I convert answer to be x variables using a loop (without .join)?

Example if answer = [3, 5, 1] It should be :

answer1 = "3"

answer2 = "5"

answer3 = "1"

2 Answers2

0

This is what you want:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer1,answer2,answer3 = [str(sum(row)) for row in matrix]
print (answer1)
print (answer2)
print (answer3)

Output:

3
5
1

If you would like to use dict:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer = {index:str(sum(row)) for index,row in enumerate(matrix)}
print(answer)

Output:

{0: '3', 1: '5', 2: '1'}

Alternatively you can use a list to store the answers:

matrix = [[1,1,1],[1,2,2],[1,0,0]]
answer = [str(sum(row)) for row in matrix]
print(answer)

Output:

['3', '5', '1']

You can refer to answer 0 with answer[0]

Alex Fung
  • 1,996
  • 13
  • 21
-1

If you actually want variables answer1 answer2 and answer3 to equal the answers, simply do this

for i in answer:
    temp='answer'+str(i+1)+' = str(answer['+str(i)+'])'
    exec(temp)
Phonzi
  • 144
  • 3
  • 9
  • Please read the question and edit your answer. `exec` is unnecessary for this simple task. – Alex Fung Mar 26 '17 at 02:20
  • @AlexFung I would argue that `exec` is necessary if the amount of numbers in the answer is not specified. The question never specified that it had to be three numbers. It just used three as an example. They also requested that the values be stored as variables. This is why I didn't use a list or dictionary which would be simpler. – Phonzi Mar 26 '17 at 15:49