从多个列表中找到正确的组合

2024-04-20 10:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有更好的方法来编写以下代码:

我想在三个列表中查找组合,abc,每个a[i]b[j]c[k]长度大于10,然后返回总长度。有没有更好的编码方法?你知道吗

from collections import namedtuple
a = ['a0', 'a1', 'a22'] 
b = ['b', 'b11111', 'b2'] 
c = ['', 'c', 'c333333333'] 

def func(**kwargs):
    nt = namedtuple('nt', ['a', 'b', 'c'])
    for  x in kwargs['a']:
        for  y in kwargs['b']:
            for  z in kwargs['c']:
                if len(x) >= len(y) >= len(z) > 10:
                    return nt(a_header=x, b_header=y, c_header=c, all_len=len(x) + len(y) + len(z))
    return ()

    #    it should return len('a22') + len('b11111') + len('c333')

Tags: 方法代码in列表forlenreturnnamedtuple
3条回答

如果len(z) = 15len(y)=13,您的代码可能会失败,例如,因为您需要len(x) >= len(y) >= len(z) > 10。相反,请尝试:

def func(**kwarg):
    nt = namedtuple('nt', ['a', 'b', 'c'])
    for  x in kwargs['a']:
        for  y in kwargs['b']:
            for  z in kwargs['c']:
                if len(x) > 10 and len(y) > 10 and len(z) > 10:
                    return nt(a_header=x, b_header=y, c_header=c, all_len=len(x) + len(y) + len(z))
return ()

如果你想that each a[i], b[j], c[k] length larger than 10。。。你知道吗

不要使用嵌套for循环。你知道吗

而是分别检查每个列表(kwargs['a'],然后kwargs['b'],然后kwargs['c']),并找到长度大于10的所有元素(元素的位置)。复杂性是O(n),其中n是所有列表的总长度。你知道吗

最后逐一计算所有可能的和或产生的和。你知道吗

使用itertools.产品我们可以为每个列表创建一个项目的所有3种方式组合。我们可以从这个产品列表中选取这些产品,并将它们过滤到只有那些分别具有lens >= (3, 6, 10)"i want 3 >= 6 >= 10" - OP的产品。你知道吗

from itertools import combinations

lista = [(x, y, z) for x, y, z in product(a, b, c)]
res = list(filter(lambda x: len(x[0]) >= 3 and len(x[1]) >= 6 and len(x[2]) >= 10, l))
print(*res)

或者对于单行解决方案使用列表理解

res = [(u, v, w) for u, v, w in product(a, b, c) if len(u) >= 3 and len(v) >= 6 and len(w) >= 10]
('a22', 'b11111', 'c333333333')

相关问题 更多 >