简体   繁体   English

如何将列表元素与元组元素匹配?

[英]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' (1) 'adsh_list_num' 中的所有元素都是 'adsh_list_sub' 的元素
(2) all elements in 'adsh_list_num' are paired to a cik element through 'adsh_cik_tuple' (2) 'adsh_list_num' 中的所有元素通过'adsh_cik_tuple' 与一个cik 元素配对

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'?如何生成一个新列表 'cik_num' 使得 'cik_num' 与 'adsh_list_num' 相同,除了它不包含 adsh 元素而是来自 'adsh_cik_tuple' 的 cik 元素?

(In this example, the string of the cik element need not always be contained in the 'adsh' element.) (在本例中,cik 元素的字符串不必总是包含在 'adsh' 元素中。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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