I’ve struggled with this question for a long time, and I didn’t find much useful information online. I tried to use for loop, but I can use it like c++ with an index like i+2 to get that element. If I have a list like [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]. There are several tuples on the list. 4 appear three times as the first element of tuples. And 2 appear three times as the second element of tuples. How can I get (4, 5), (4, 6), (4, 7) and [(0, 2), (1, 2), (2, 2)out from the list because they have the same element of the tuple?
>Solution :
You can use filter here
lst = [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]
same_first = 4
new_lst = list(filter(lambda e:e[0]==same_first,lst))
print(new_lst)
Or Make a function.
lst = [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]
def same(lst,same_number,choice):
return list(filter(lambda e:e[choice]==same_number,lst))
# change choice to 0 for first and 1 for second
print(same(lst=lst,same_number=2,choice=1)) # [(4, 5), (4, 6), (4, 7)]
print(same(lst=lst,same_number=2,choice=1)) # [(0, 2), (1, 2), (2, 2)]