One Array separation based on second array index value in python

Omkar

I have following torque and speed arrays in python. My question is how can I get corresponding torque values for given speed (Each Torque index is correspond to each speed index). For ex, Speed 1 will have Torque 10, 30, 50 and Speed 7 will have Torque 20 so on.


Torque = [10, 20, 30, 40, 50]

Speed = [1, 7, 1, 8, 1]


I tried using Tuple with following code and output, but I cant able to separate Torques for given speed. For ex, at 1 speed Trq = [10, 30, 50]. Help is most appreciated.


Trq_Speed = list(zip(Speed, Torque))
Trq_Speed.sort(key=lambda x: x[0])
print(Trq_Speed)

[(10, 1), (30, 1), (50, 1), (20, 7), (40, 8)]

thaavik

Use enumerate and a defaultdict.

from collections import defaultdict
d = defaultdict(list)
Torque = [10, 20, 30, 40, 50]
Speed = [1, 7, 1, 8, 1]
for i, e in enumerate(Speed):
    d[e].append(Torque[i])
d

returns:

defaultdict(list, {1: [10, 30, 50], 7: [20], 8: [40]})

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Change Values in One Array, Based On Value from Column of Second Array

Masking nested array with value at index with a second array

Drop the index position of a second array based on the first

Return first value of array based on second value

Seek one value in Array and return the second one

Sort index of array based on value

Rendering checkboxes based on one array, and checked elements based on the second array

Return the index of the second distinct value in an array?

How to sort an array based on the second value with javascript?

With PySpark dataframe locate value from one array based on index and copy to another array

Find index of second array and get record based on that index

Sorting nested array based on second value in the inner array in Javascript

Removing array duplicates based on second array item value

Update the first array object value based on the second array by comparing a field

Sort array based on order value within second array

Sort array in to several based on value from second array

Replace value in one array with matching properties from second array

How to convert initials in one array to match a value in a second array

Python change index for value array

Union two dimensional array based on index value

Find index in array based on given value

Changed value in numpy array based on index and on criteria

Sort multidimensional array based on the value of a particular index

Jackson Deserialization based on array index or key value

Find a certain index in an array based on a particular value

Index array based on value limits of another

Sorting array based on index of minimum value?

remove the common elements in array based on index value

Increment value of map based on array lookup index