1
\$\begingroup\$

Example: I want to select tuple in an array(t_bet), which contains just one element from judge_tpl = (5,12,24). For example, (3, 4, 5, 16, 30) is ok while (3, 12, 24, 29, 30) is not because it contains two elements.

t_bet = [(3, 12, 24, 29, 30),
 (3, 13, 18, 19, 22),
 (1, 11, 16, 17, 22),
 (3, 4, 5, 16, 30),
 (1, 11, 15, 20, 24)]

lst = []
for i in t_bet:
    if (5 in i) and (12 not in i) and (24 not in i ) :
        lst.append(i)
    elif (5 not in i) and (12 in i) and (24 not in i ):
        lst.append(i)
    elif (5 not in i) and (12 not in i) and (24 in i ):
        lst.append(i)

lst: [(3, 4, 5, 16, 30), (1, 11, 15, 20, 24)]

I have to list all combinations using if..elif,which is inconvenient especially when there are so many elements in judge_tpl.

Notice: The tuples in t_bet have same lengths while there are more than 10 elements in judge_tpl.

\$\endgroup\$
3
  • \$\begingroup\$ @BillalBEGUERADJ I have updated but I think the number of tuples and the length do not affect the result. \$\endgroup\$
    – Jack
    Commented May 28, 2018 at 13:01
  • \$\begingroup\$ [bet for bet in t_bet if len(set(bet) & set(judge_tpl)) == 1] \$\endgroup\$ Commented May 28, 2018 at 13:51
  • 1
    \$\begingroup\$ Do duplicates matter? \$\endgroup\$
    – Ludisposed
    Commented May 28, 2018 at 14:04

1 Answer 1

1
\$\begingroup\$
  1. You don't need parenthesis around the conditions in your if statements

    if x in y and another_x in y is the same as if (x in y) and (another_x in y)

  2. Use list comprehensions when possible see PEP8#202

  3. Use intersection of sets to get how many elements occur in both tuples

    If duplicated don't matter (as they do not in your code) it is possible to convert the tuples into sets and check if the intersection between the sets are 1 (Meaning there is only 1 element that occurs in both) Like @Maarten Fabré suggested


JUDGE = (5, 12, 24)

def valid_bet(bets):
    return [bet for bet in bets if len(set(bet) & set(JUDGE)) == 1]
    # return [bet for bet in best if len(set(bet).intersection(set(JUDGE))) == 1]
    # set_a & set_b == set_a.intersection(set_b)

if __name__ == "__main__":
    bets = [(3, 12, 24, 29, 30),
            (3, 13, 18, 19, 22),
            (1, 11, 16, 17, 22),
            (3, 4, 5, 16, 30),
            (1, 11, 15, 20, 24)]
    print(valid_bet(bets))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.