Col
Col

Reputation: 33

Test if tuple exist in python list

I have a given python list as follows.

given_list = [
    (4, 6, 28, 9, 2, 26, 0),
    (4, 6, 28, 9, 2, 26, 15),
    (4, 6, 28, 9, 2, 7, 15),
    (4, 6, 28, 9, 26, 0, 15),
    (4, 6, 28, 2, 26, 0, 15),
    (4, 6, 9, 2, 26, 0, 15),
    (4, 28, 9, 2, 26, 0, 15),
    (6, 28, 9, 2, 26, 0, 15),
]

I have a reference list as follows.

ref_list = [
    (7, 28),  # has 1 in Lists
    (57, 2),  # has 0 in Lists
    (6, 9, 0),  # has 2 in Lists
    (6, 28, 9, 2, 26, 0),  # has 1 in Lists
]

I need to extract some tuples from the given list, if the tuple contains all the elements for any tuple from the reference list

I tried as follows.

for item in given_list:
    for ref in ref_list:
        if all(ref) in item:
            print(item)

But, wrong.

(4, 6, 28, 9, 2, 26, 0)
(4, 6, 28, 9, 2, 26, 0)
(4, 6, 28, 9, 26, 0, 15)
(4, 6, 28, 9, 26, 0, 15)
(4, 6, 28, 2, 26, 0, 15)
(4, 6, 28, 2, 26, 0, 15)
(4, 6, 9, 2, 26, 0, 15)
(4, 6, 9, 2, 26, 0, 15)
(4, 28, 9, 2, 26, 0, 15)
(4, 28, 9, 2, 26, 0, 15)
(6, 28, 9, 2, 26, 0, 15)
(6, 28, 9, 2, 26, 0, 15)

Expected is:

# [(4, 6, 28, 9, 2, 26, 0), 
#  (4, 6, 28, 9, 2, 7, 15),
#  (4, 6, 28, 9, 26, 0, 15),
#  (4, 6, 9, 2, 26, 0, 15),
#  (6, 28, 9, 2, 26, 0, 15)]

Upvotes: 0

Views: 131

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24289

You can do it efficiently using sets:

given_list = [
    (4, 6, 28, 9, 2, 26, 0),
    (4, 6, 28, 9, 2, 26, 15),
    (4, 6, 28, 9, 2, 7, 15),
    (4, 6, 28, 9, 26, 0, 15),
    (4, 6, 28, 2, 26, 0, 15),
    (4, 6, 9, 2, 26, 0, 15),
    (4, 28, 9, 2, 26, 0, 15),
    (6, 28, 9, 2, 26, 0, 15),
]

ref_list = [
    (7, 28),  # has 1 in given_list
    (57, 2),  # has 0 in given_list
    (6, 9, 0),  # has 2 in given_list
    (6, 28, 9, 2, 26, 0),  # has 1 in given_list
]

ref_sets = [set(tup) for tup in ref_list]

out = [tup for tup in given_list if any(s.issubset(tup) for s in ref_sets)]
print(out)

# [
#     (4, 6, 28, 9, 2, 26, 0), 
#     (4, 6, 28, 9, 2, 7, 15),
#     (4, 6, 28, 9, 26, 0, 15),
#     (4, 6, 9, 2, 26, 0, 15),
#     (6, 28, 9, 2, 26, 0, 15),
# ]

Note that you expected output lacked the first tuple, which contains 6, 9 and 0.

Upvotes: 2

Related Questions