简体   繁体   中英

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'?

(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']

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'
]

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