简体   繁体   中英

How do I get the index of the common integer element from two separate lists and plug it to another list?


I have 3 lists.

A_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Q_act = [2, 3]
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

All lists are integers.

What I am trying to do is to compare Q_act with A_set then obtain the indices of the numbers that match from A_set .

(Example: Q_act has the elements [2,3] it is located in indices [1,2] from A_set )

Afterwards, I will use those indices to obtain the corresponding value in dur and store this in a list called p_dur_Q_act .

(Example: using the result from the previous example, [1,2]

The values in the dur list corresponding to the indices [1,2] should be stored in another list called p_dur_Q_act

ie [4,5] should be the values stored in the list p_dur_Q_act )

So, how do I get the index of the common integer element (which is [1,2] ) from two separate lists and plug it to another list?


So far here are the code(s) I used:

This one, I wrote because it returns the index. But not [4,5] .

p_Q = set(Q_act).intersection(A_set)
    p_dur_Q_act = [i + 1 for i, x in enumerate(p_Q)]
    print(p_dur_Q_act)

I also tried this but I receive an error TypeError: argument of type 'int' is not iterable

 p_dur_Q_act = [i + 1 for i, x in enumerate(Q_act) if any(elem in x for elem in A_set)]
    print(p_dur_Q_act)

Use index function to get the index of the element in the list.

>>> a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> q_act = [2, 3]
>>> dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]
>>>
>>> print([dur[a_set.index(q)] for q in set(a_set).intersection(q_act)])

[4, 5]

Another option is to use the enumerate iterator to generate every index, and then select only the ones you want:

a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = [2, 3]    
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [i for i,v in enumerate(a_set) if v in q_act]

print([dur[p] for p in p_dur_q_act if p in dur]) # [4, 5]

This is more efficient than repeatedly calling index if the number of matches is large, because the number of calls is proportional to the number of matches, but the duration of calls is proportional to the length of a_set. The enumerate approach can be made even more efficient by turning q_act into a set, since in scales better with sets than lists. At these scales, though, there will be no observable difference.

You don't need to map these to index values, though. You can get the same result if you use zip to map a_set to dur and then select the d values whose a values are in q_act .

a_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
q_act = {2, 3}    
dur = [0, 4, 5, 2, 1, 3, 4, 8, 2, 3]

p_dur_q_act = [d for a, d in zip(a_set, dur) if a in q_act]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM