如何提取 python 中另一个列表中存在的嵌套元组列表的编号

How to extract numbers of a nested list of tuples which exist in another list in python

我在 python 中有一个嵌套列表,想从中提取一些数字。每个子列表包含元组,每个元组有两个数字,第一个总是 2。我想从子列表中提取第二个元组数,它们所有元组的第二个数存在于另一个列表 (check_values) 中。这是我的数据:

points=[[(2, 12), (2, 11)], [(2, 3), (2, 5), (2, 0), (2, 2)],\
        [(2, 0), (2, 19), (2, 5)], [(2, 18), (2, 20)]]
check_values=[0, 1, 2, 3, 5, 10, 11, 17, 18, 20]

由于我的数据仅显示来自第二个(3, 5, 0, 2)和最后一个(18, 20)的元组的第二个值,子列表存在于 check_values 中。所以,我的结果应该是:

extracted=[[3, 5, 0, 2], [18, 20]]

我尝试了以下但没有成功:

extracted=[]
for i in points:
    for j in i:
        if j[1] in check_values:
            extracted.append (i)

非常感谢提前提供的任何帮助。

extracted = []

# for each sublist...
for sublist in points:
    # get the second values of each tuple
    second_vals = [sec for fir, sec in sublist]

    # check if "all" of the values in `second_vals` are in `check_values`
    if all(val in check_values for val in second_vals):
        # store the `second_vals` if so
        extracted.append(second_vals)

得到

>>> extracted
[[3, 5, 0, 2], [18, 20]]

虽然 Mustafa 的回答完全正确,但这里有另一个变体:

# This extracts the second values that are in the check_values list
# That is: [[11], [3, 5, 0, 2], [0, 5], [18, 20]]
extracted = [ [pair[1] for pair in sublist if pair[1] in check_values] for sublist in points]

# The second step filters out those sublists whose size is different, i.e. not
# all second values are in the check_values list
extracted = [ x for i, x in enumerate(extracted) if len(x) == len(points[i]) ]

最后我们得到:

[[3, 5, 0, 2], [18, 20]]

这是另一种方法:

points=[[(2, 12), (2, 11)], [(2, 3), (2, 5), (2, 0), (2, 2)],\
        [(2, 0), (2, 19), (2, 5)], [(2, 18), (2, 20)]]
check_values=[0, 1, 2, 3, 5, 10, 11, 17, 18, 20]

extracted_value=[]
def check_2nd_value(sublist:list):
    """
    This method will get the sublist and 
    check the availability of 2nd items of every tuple in check_value (given list)
    """
    # gets 2nd item of the tuples
    tple_item2 = [tple[1] for tple in sublist]
    # if the difference between two set is empty
    # then all values are available in 2nd list
    diff = set(tple_item2).difference(set(check_values))
    if diff:
        return 
    else:
        return tple_item2

# finding all the lists - for configured option
for sublist in points:
    found_items = check_2nd_value(sublist)
    # if found_items is not None then -> append the list
    if found_items:
        extracted_value.append(found_items)

提取的值为:

print(extracted_value)
[[3, 5, 0, 2], [18, 20]]