The zip function is useful here, used with a list comprehension.
[x + y for x, y in zip(first, second)]
If you have a list of lists (instead of just two lists):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
Answer from tom on Stack OverflowThe zip function is useful here, used with a list comprehension.
[x + y for x, y in zip(first, second)]
If you have a list of lists (instead of just two lists):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
Default behavior in numpy.add (numpy.subtract, etc) is element-wise:
import numpy as np
np.add(first, second)
which outputs
array([7,9,11,13,15])
How to sum the elements of 2 lists in python? - Stack Overflow
python - Two sum with two lists - Code Review Stack Exchange
python - Modify a code to sum two lists (element-wise) - Stack Overflow
Fastest way to sum two lists of items with each other in python - Stack Overflow
Hi, I'm trying to create a function which adds together items from two lists and I can't figure out what I'm doing wrong. My initial code was very similar to this but did not work, after googling other people's solutions I've essentially copy and pasted what multiple people on various forums advised, but still have not had any success. Currently it just prints out a blank list, "[ ]", and I don't know why. Can anyone help?
def list_sum(a, b):
a = []
b = []
c = []
for i in range(len(a)):
listAdd = (a[i] + b[i])
c.append(listAdd)
return(c)
if __name__ == "__main__":
a = [1, 2, 3]
b = [4, 5, 6]
add = list_sum(a, b)
print(add)you can use zip/map:
result = list(map(sum,zip(list1,list2)))
Alternative, via list_comprehension:
result = [i+j for i,j in zip(list1,list2)]
OUTPUT:
[11, 13, 15, 17, 19]
Use the vectorised operations from numpy
import numpy as np
newlist = list(np.array(list1) + np.array(list2))
Assuming that your lists are sorted and this is something that comes out of problem description and the part where you need to find something in 99% of that kind of questions you want to use binary search. So basically all your code could be written like this:
from bisect import bisect_left
def binary_search(a, x):
pos = bisect_left(a, x)
return pos if pos != len(a) and a[pos] == x else -1
def two_sum(a, b, target):
result = []
for num in a:
index = binary_search(b, target-num)
if index != -1:
result.append((num, b[index]))
return result
Now if you want to save some memory, you might want to make two_sum a generator, which will make it look like this:
def two_sum(a, b, target):
result = []
for num in a:
index = binary_search(b, target-num)
if index != -1:
yield num, b[index]
I cannot really call my answer a review to your code because I completely overwrote a solution for this. But as I mentioned in the beginning whenever a problem says something about sorted lists and searching on it, most likely you will use bsearch in your solution.
I re-constructed your algorithm using generators, which I find easier on the eyes (instead of indexing) for these sort of list traversals. Other than that, the code is the same.
def two_sum(list1, list2, target):
# Get a generator for each list
l1 = iter(list1)
l2 = reversed(list2)
# loop and append to results list
result = []
try:
# get the first sample from each list
x = next(l1)
y = next(l2)
while True:
# If we find a match, record it
if x + y == target:
new_pair = x, y
result.append(new_pair)
# get next unique elements
x = next(l1)
while x == new_pair[0]:
x = l1.next()
y = next(l2)
while y == new_pair[1]:
y = next(l2)
# if no match, then get new element from one list
elif x + y > target:
y = next(l2)
else:
x = next(l1)
# when one of the generators runs out of elements it will assert
except StopIteration:
pass
return result
print(two_sum([1, 3, 5, 7], [2, 3, 3, 5], 6))
You can try this:
L1 = [[1,2,3], [4,5,6], [7,8,9]]
L2 = [[10,20,30], [40,50,60], [70,80,90]]
final_list = [[c+d for c, d in zip(a, b)] for a, b in zip(L1, L2)]
Output:
[[11, 22, 33], [44, 55, 66], [77, 88, 99]]
Using zip and map with list comprehension :
>>> temp = zip(L1, L2)
# >>> list(temp)
# => [([1, 2, 3], [10, 20, 30]), ([4, 5, 6], [40, 50, 60]), ([7, 8, 9], [70, 80, 90])]
>>> [list(map(sum, zip(x,y))) for x,y in temp]
=> [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
NOTE : using just zip(L1, L2) is better than doing list(zip(L1, L2)) as the former returns a Generator which is more efficient and faster than building a list.
the longer a key is pressed down, the higher a counter for said key increases
Unless your users have 300 fingers, they likely would only be pressing up to ten keys at a time. You can register for keydown and keyup events; save the frame counter or the return value of time()/clock() on the array when a key is down; and when a key is up or when you need to find the current value of the key, subtract the differences. This will reduce the number of loops to around 10 rather than 300. Note that depending on the system, time()/clock() may be a syscall, which can be slow, so using frame counter may be preferable.
counter = 0
keys = {}
while True:
for event in pygame.event.get() :
if event.type == pygame.KEYDOWN :
keys[event.key] = counter
elif event.type == pygame.KEYUP :
diff[event.key] = keys.pop(event.key) - counter
counter += 1
But I highly doubt that this is the bottleneck of your game.
This will work nicely in Python 3.x
list3 = [x+y if x and y else 0 for x, y in zip(list1, list2)]
Or, if you're using Python 2.x:
import itertools as it
list3 = [x+y if x and y else 0 for x, y in it.izip(list1, list2)]