1

I was't really sure how to ask this. I have a list of 3 values initially set to zero. Then I read 3 values in at a time from the user and I want to update the 3 values in the list with the new ones I read.

cordlist = [0]*3

Input: 3 4 5

I want list to now look like: [3, 4, 5]

Input: 2 3 -6

List should now be [5, 7, -1]

How do I go about accomplishing this? This is what I have:

cordlist += ([int(g) for g in raw_input().split()] for i in xrange(n))

but that just adds a new list, and doesn't really update the values in the previous list

jamylak
  • 128,818
  • 30
  • 231
  • 230
smac89
  • 39,374
  • 15
  • 132
  • 179

5 Answers5

2
In [17]: import numpy as np

In [18]: lst=np.array([0]*3)

In [19]: lst+=np.array([int(g) for g in raw_input().split()])

3 4 5

In [20]: lst
Out[20]: array([3, 4, 5])

In [21]: lst+=np.array([int(g) for g in raw_input().split()])

2 3 -6

In [22]: lst
Out[22]: array([ 5,  7, -1])
namit
  • 6,780
  • 4
  • 35
  • 41
1

I would do something like this:

cordlist = [0, 0, 0]
for i in xrange(n):
    cordlist = map(sum, zip(cordlist, map(int, raw_input().split())))

Breakdown:

  • map(int, raw_input().split()) is equivalent to [int(i) for i in raw_input().split()]
  • zip basically takes a number a lists, and returns a list of tuples containing the elements that are in the same index. See the docs for more information.
  • map, as I explained earlier, applies a function to each of the elements in an iterable, and returns a list. See the docs for more information.
Volatility
  • 31,232
  • 10
  • 80
  • 89
1
cordlist = [v1+int(v2) for v1, v2 in zip(cordlist, raw_input().split())]

tested like that:

l1 = [1,2,3]
l2 = [2,3,4]
print [v1+v2 for v1, v2 in zip(l1, l2)]

result: [3, 5, 7]

insys
  • 1,288
  • 13
  • 26
0

I would go that way using itertools.zip_longest:

from itertools import zip_longest

def add_lists(l1, l2):
    return [int(i)+int(j) for i, j in zip_longest(l1, l2, fillvalue=0)]

result = []
while True:  
    l = input().split()
    print('result = ', add_lists(result, l))

Output:

>>> 1 2 3
result =  [1, 2, 3]
>>> 3 4 5
result =  [4, 6, 8] 
aldeb
  • 6,588
  • 5
  • 25
  • 48
0

More compact version of @namit's numpy solution

>>> import numpy as np
>>> lst = np.zeros(3, dtype=int)
>>> for i in range(2):
        lst += np.fromstring(raw_input(), dtype=int, sep=' ')


3 4 5
2 3 -6
>>> lst
array([ 5,  7, -1])
jamylak
  • 128,818
  • 30
  • 231
  • 230