Python 3.6 - is there a condition that can behave like otherwise? -
my example (list , b same size):
a = ['12','12','12','12','12','23','24','24','31','31'] b = ['1','2','2','2','2','2','5','5','5','5'] c = a, b
here code needs otherwise condition, c[0] code looks through list rather both lists , prints out result of list , b fit condition. the else condition in code wrong , cant think of alternative:
d = list(zip(*[(ai,bi) ai, bi in zip(a,b) if c[0].count(ai) == 5 else 2])) e = list(zip(*[(ai,bi) ai, bi in zip(a,b) if c[0].count(ai) == 7 else 2]))
is possible change condition prints counts of 5 if there more 2 counts in example? or prints counts of 2 if 7 initial count there none detected?
my desired outcome:
d = [('12','12','12','12','12',), ('1','2','2','2','2')] e = [('24','24','31','31'), ('5','5','5','5')]
thank you!
you need count elements first, decide ones selecting. use collections.counter()
object count elements efficiently, can decide elements picked:
from collections import counter counts = counter(a) has_5 = any(c == 5 c in counts.values()) has_7 = any(c == 7 c in counts.values())
now know if there element appears 5 times, , if there element appears 7 times. can filter elements how many times appear, without re-counting each iteration. make pick first, don't have complicate if
logic:
desired_count = 5 if has_5 else 2 d = list(zip(*[(ai,bi) ai, bi in zip(a,b) if counts[ai] == desired_count])) desired_count = 7 if has_7 else 2 e = list(zip(*[(ai,bi) ai, bi in zip(a,b) if counts[ai] == desired_count]))
so if there element appears 5 times, filter on those, otherwise filter on elements appear twice.
demo:
>>> collections import counter >>> = ['12','12','12','12','12','23','24','24','31','31'] >>> b = ['1','2','2','2','2','2','5','5','5','5'] >>> counts = counter(a) >>> has_5 = any(c == 5 c in counts.values()) >>> has_7 = any(c == 7 c in counts.values()) >>> desired_count = 5 if has_5 else 2 >>> list(zip(*[(ai,bi) ai, bi in zip(a,b) if counts[ai] == desired_count])) [('12', '12', '12', '12', '12'), ('1', '2', '2', '2', '2')] >>> desired_count = 7 if has_7 else 2 >>> list(zip(*[(ai,bi) ai, bi in zip(a,b) if counts[ai] == desired_count])) [('24', '24', '31', '31'), ('5', '5', '5', '5')]
Comments
Post a Comment