我的例子(列出a和b的大小总是相同):
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
这是我的代码,需要类似于其他条件的东西,c [0]是这样代码只查看列表而不是两个列表,并打印出符合条件的列表a和b的结果。 此代码中的else条件错误,我无法想到替代:
d = list(zip(*[(ai,bi) for ai, bi in zip(a,b) if c[0].count(ai) == 5 else 2]))
e = list(zip(*[(ai,bi) for ai, bi in zip(a,b) if c[0].count(ai) == 7 else 2]))
是否可以更改条件,以便在我的示例中,如果计数超过2,则仅打印5个计数?或者,如果7是初始计数但是没有检测到,则只打印2的计数?
我想要的结果:
d = [('12','12','12','12','12',), ('1','2','2','2','2')]
e = [('24','24','31','31'), ('5','5','5','5')]
谢谢!
答案 0 :(得分:3)
您需要先计算第一个元素,然后决定选择哪些元素。使用collections.Counter()
object有效地计算元素,然后您可以决定要选择哪些元素:
from collections import Counter
counts = Counter(a)
has_5 = any(c == 5 for c in counts.values())
has_7 = any(c == 7 for c in counts.values())
现在您知道是否有一个元素出现5次,并且是否有一个元素出现7次。您现在可以按照它们出现的次数过滤这些元素,而无需重新计算每次迭代。首先选择 ,这样就不必使if
逻辑变得复杂:
desired_count = 5 if has_5 else 2
d = list(zip(*[(ai,bi) for ai, bi in zip(a,b) if counts[ai] == desired_count]))
desired_count = 7 if has_7 else 2
e = list(zip(*[(ai,bi) for ai, bi in zip(a,b) if counts[ai] == desired_count]))
所以如果如果有一个元素出现5次,请对其进行过滤,否则过滤仅出现两次的元素。
演示:
>>> from collections import Counter
>>> a = ['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 for c in counts.values())
>>> has_7 = any(c == 7 for c in counts.values())
>>> desired_count = 5 if has_5 else 2
>>> list(zip(*[(ai,bi) for 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) for ai, bi in zip(a,b) if counts[ai] == desired_count]))
[('24', '24', '31', '31'), ('5', '5', '5', '5')]