Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I match list elements with tuple elements?

I have the following lists and tuple lists:

adsh_list_sub
['0000007084-22-000008', '0000766421-22-000009', '0000320193-22-000007']
cik_list
['7084', '766421', '320193']
adsh_cik_tuple
[('0000007084-22-000008', '7084'),
 ('0000766421-22-000009', '766421'),
 ('0000320193-22-000007', '320193')]
adsh_list_num
['0000007084-22-000008',
 '0000007084-22-000008',
 '0000320193-22-000007',
 '0000320193-22-000007',
 '0000766421-22-000009',
 '0000766421-22-000009',
 '0000320193-22-000007',
 '0000320193-22-000007',
 '0000007084-22-000008',
 '0000007084-22-000008',
 '0000007084-22-000008',
 '0000007084-22-000008',
 '0000007084-22-000008',
 '0000007084-22-000008',
 '0000320193-22-000007',
 '0000320193-22-000007',
 '0000007084-22-000008']

Note that
(1) all elements in ‘adsh_list_num’ are elements of ‘adsh_list_sub’
(2) all elements in ‘adsh_list_num’ are paired to a cik element through ‘adsh_cik_tuple’

How can I generate a new list ‘cik_num’ such that ‘cik_num’ is identical to ‘adsh_list_num’ except that it contains not the adsh element but the cik element from ‘adsh_cik_tuple’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(although the case in this example, the string of the cik element need not always be contained in the ‘adsh’ element.)

Expected output: 
['7084',
 '7084',
 '320193',
 '320193',
 '766421',
 '766421',
 '320193',
 '320193',
 '7084',
 '7084',
 '7084',
 '7084',
 '7084',
 '7084',
 '320193',
 '320193',
 '7084']

>Solution :

You can create a dictionary from the list of tuples, and then use a list comprehension to read off the result using the generated mapping:

mapping = dict(adsh_cik_tuple)
[mapping[item] for item in adsh_list_num]

This outputs:

[
 '7084', '7084', '320193', '320193', '766421', '766421', '320193', '320193', 
 '7084', '7084', '7084', '7084', '7084', '7084', '320193', '320193', '7084'
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading