I have two lists...
depth = [1, 2, 3, 2, 1]
direction = ['x', 'y', 'z', 'x', 'x']
I want to compare the two of these lists and for each instance of direction == 'x', continually add the corresponding values in depth together. So I should get a value of 4 since 1 2 1 = 4 and it corresponds to each 'x' string in list direction.
The lists depth and direction are greatly abbreviated for example purposes. I want to iterate over both lists and in reality they contain a couple thousand values each.
I have already created a zip() and tried working with it like this:
dndzip = zip(depth, direction)
x = 0
for i,j in dndzip:
if i == 'x':
x = j
return x
print(x)
I actually had this for loop under a defined function, but unfortunately this for loop doesn't return the proper value. I get a value and no errors, but it's always a value of 2 and not sure where I'm going wrong here.
CodePudding user response:
You can use dict.setdefault
to add each direction's corresponding depth iteratively:
d = {}
for i,j in zip(direction, depth):
d.setdefault(i, 0)
d[i] = j
out = list(d.items())
Alternatively you can use collections.defaultdict
:
from collections import defaultdict
d = defaultdict(int)
for i,j in zip(direction, depth):
d[i] = j
out = list(d.items())
Output:
[('x', 4), ('y', 2), ('z', 3)]
CodePudding user response:
I'm not sure why you're getting 2 exactly, as when I ran the above code I got 0. But the reason for that is because in your loop, when you're decompressing your list with
dndzip = zip(depth, direction)
for i,j in dndzip:
notice that you zipped your list with depth as the first argument, so in this case i is depth and j is direction, so x =j is never run because i (depth) is never 'x'. To fix this, you would do:
dndzip = zip(depth, direction)
x = 0
for j,i in dndzip:
if i == 'x':
x = j
print(x)
CodePudding user response:
In your particular code, it looks like you have the i
and j
mixed up. When you do dndzip = zip(depth, direction)
, dndzip
is going to contain tuples where the first item is the item from depth
, and the second is the one from direction
. Meaning that something like
def sum_x_depths(depth, direction):
dndzip = zip(depth, direction)
x = 0
for i,j in dndzip:
if i == 'x':
x = j
return x
will fail, since things like if i == 'x':
are comparing i
, which is an int
, to 'x'
which is a str
. Then x = i
also fails, because j
is a str
and x
is an int
. Make sure to try and make variable names refer to what they represent!
def sum_x_depths(depths, directions):
s = 0
for depth, direction in zip(depths, directions):
if direction == 'x':
s = depth
return s
You can also use the sum
function and generator comprehensions to nice effect here, though it might be a bit long on a single line with these names:
def sum_x_depths(depths, directions):
return sum(depth for depth, direction in zip(depths, directions) if direction == 'x')