lst = [(2),('hello',3),(4),('world',5)]
I want extract only the tuples that have the value 3 and above
how can i do that ?
CodePudding user response:
[n for n in lst if type(n) is tuple and n[1] >= 3]
[n for n in lst if isinstance(n, tuple) and n[1] >= 3 or isinstance(n, int) and n >= 3]
CodePudding user response:
Try this:
lst = [(2),('hello',3),(4),('world',5)]
res = []
for tpl in lst:
# check type(tpl)==tuple
# and all elements in tpl not in range(3) -> [0,1,2] -> (larger than 3)
if isinstance(tpl, tuple) and all(item not in range(3) for item in tpl):
res.append(tpl)
# check elements that is not 'tuple' like (2) and (4)
# (2) is not tuple, (2,) is a tuple with single element
elif tpl not in range(3):
res.append(tpl)
print(res)
Output: [('hello', 3), 4, ('world', 5)]
CodePudding user response:
Accounting for (4)
not being a tuple, and the value greater than or equal to 3
potentially being anywhere in each tuple:
[n
for n in lst
if (isinstance(n, int) and n >= 4) or \
(isinstance(n, tuple) and \
any(x for x in n if isinstance(x, int) and x >= 3))]
# [('hello', 3), 4, ('world', 5)]
CodePudding user response:
This will handle the cases you need. I made it so that you get the tuples first. It's more object oriented than other answers.
from typing import List
class More:
def __init__(self):
self.value = 0
def be(self, value: int):
self.value = value
return self
def than(self, value: int):
if value >= self.value:
return value
return None
class TupleHandlr:
@staticmethod
def is_tuple(t):
return isinstance(t, tuple)
def larger_numbers(liszt):
numbrz = [n for n in liszt if isinstance(n,int)]
more = More().be(3)
largernumbrz = [n for n in numbrz if more.than(n)]
return largernumbrz
class TupleValueExtractr:
def __init__(self):
self.MinimumValue = 3
def from_list(self, liszt: List) -> List:
th = TupleHandlr()
tuples = [t for t in liszt if th.is_tuple(t)]
more = More().be(self.MinimumValue)
largertuples = [t for t in tuples if more.than(t[1])]
return largertuples larger_numbers(liszt)
lst = [(2), ('hello', 3), (4), ('world', 5)]
extract = TupleValueExtractr()
print(extract.from_list(lst))
Output:
[('hello', 3), ('world', 5), 4]