2 lists manipulated for a 3rd list
Question:
If I have a list of directions:
LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
plus a list of random directions:
LIST_B=['E','NNE','S','SSE','SW','N']
How do I arrive a list that looks at the directions in LIST_B and returns the opposite direction – plus one increment in the clockwise direction.
For example, the code would look at the first element in LIST_B (‘E’) – return the opposite direction (‘W’) plus one increment in the clockwise direction – which would be ‘WNW’.
DESIRED_LIST=['WNW','SW','NNE','N','ENE','SSW']
Thankyou
Answers:
You can use modulo arithmetic:
out = []
for v in LIST_B:
idx = LIST_A.index(v)
out.append(LIST_A[(idx + 8 + 1) % len(LIST_A)]) # 8 for opposite, 1 for increment to clockwise direction
print(out)
Prints:
['WNW', 'SW', 'NNE', 'N', 'ENE', 'SSW']
It is easiest if you first convert the direction to an index and then perform the operations on it. So it’s something like this:
LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
LIST_B=['E','NNE','S','SSE','SW','N']
# iterate over all directions in LIST_B
for direction in LIST_B:
# get index of element in LIST_A
index = LIST_A.index(direction)
# turn by 180 degrees
index += len(LIST_A)//2
# add one increment in clockwise direction
index += 1
# modulo for directions with over 360 degrees
index %= len(LIST_A)
# output result
print(LIST_A[index])
If I have a list of directions:
LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
plus a list of random directions:
LIST_B=['E','NNE','S','SSE','SW','N']
How do I arrive a list that looks at the directions in LIST_B and returns the opposite direction – plus one increment in the clockwise direction.
For example, the code would look at the first element in LIST_B (‘E’) – return the opposite direction (‘W’) plus one increment in the clockwise direction – which would be ‘WNW’.
DESIRED_LIST=['WNW','SW','NNE','N','ENE','SSW']
Thankyou
You can use modulo arithmetic:
out = []
for v in LIST_B:
idx = LIST_A.index(v)
out.append(LIST_A[(idx + 8 + 1) % len(LIST_A)]) # 8 for opposite, 1 for increment to clockwise direction
print(out)
Prints:
['WNW', 'SW', 'NNE', 'N', 'ENE', 'SSW']
It is easiest if you first convert the direction to an index and then perform the operations on it. So it’s something like this:
LIST_A=['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
LIST_B=['E','NNE','S','SSE','SW','N']
# iterate over all directions in LIST_B
for direction in LIST_B:
# get index of element in LIST_A
index = LIST_A.index(direction)
# turn by 180 degrees
index += len(LIST_A)//2
# add one increment in clockwise direction
index += 1
# modulo for directions with over 360 degrees
index %= len(LIST_A)
# output result
print(LIST_A[index])