简体   繁体   中英

How to change a list of tuples to a set in Python?

I created a function in Python which returns a list of all the possible outcomes of throwing 2 dice. The list of tuples: [(1,1), (1,2), ..., (6,6)].

Then I wrote a function to find all elements of which the sum of the two values is even (a) and another one to find the elements of which the product of the values is even (b) .

Now I'm trying to write a function to find the elements that are only in (a) and another one to find the elements of which the product of the values is even in both (a) and (b) .

 def dice_outcomes(): outcomes=[] for i in range (1,7): for j in range (1,7): outcomes.append((i,j)) r = outcomes return(r) def filter_sumiseven(tuple): elem1 = tuple[0] elem2 = tuple[1] return (elem1 + elem2)%2 == 0 def filter_productiseven(tuple): elem1 = tuple[0] elem2 = tuple[1] return (elem1 * elem2)%2 == 0 

I tried to convert my list (see below) to a set but it still does not work. I first tried to make a variable a and b for the return of my 2nd and 3rd function but that didn't work. Could anyone explain how to get the correct output?

  def only_as(a): set_a = set(a) set_b = set(b) if set_a not in set_b: return set_a else: #DO NOT ADD def a_and_b(a, b): set_a = set(a) set_b = set(b) if set_a in set_b: #print if set_b in set_a : #print 

Thanks a lot for your help!

You can simplify your code to be:

from itertools import product

dice_outcomes = list(product(range(1, 7), repeat=2))
is_even = {el for el in dice_outcomes if sum(el) % 2 == 0}
product_is_even = {(fst, snd) for fst, snd in dice_outcomes if fst*snd % 2 == 0}
just_even = is_even - product_is_even
even_and_product = is_even & product_is_even

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