这个嵌套列表理解有什么问题?

时间:2011-11-28 05:15:07

标签: python python-3.x list-comprehension

>>> c = 'A/B,C/D,E/F'
>>> [a for b in c.split(',') for (a,_) in b.split('/')]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ValueError: need more than 1 value to unpack

预期结果为['A', 'C', 'E']

这就是我期望的方式,但显然它已经在Python中回归:

>>> [a for (a, _) in b.split('/') for b in c.split(',')]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

2 个答案:

答案 0 :(得分:5)

你失败的原因是b.split('/')没有产生2元组。 双列表理解意味着您希望将笛卡儿乘积视为平流而不是矩阵。即:

>>> [x+'/'+y for y in 'ab' for x in '012']
['0/a', '1/a', '2/a', '0/b', '1/b', '2/b']
    # desire output 0,1,2
    # not output 0,1,2,0,1,2

您不是在寻找6个答案,而是在寻找3.您想要的是:

>>> [frac.split('/')[0] for frac in c.split(',')]
['A', 'C', 'E']

即使您使用了嵌套列表解析,您也可以获得笛卡尔积(3x2 = 6)并意识到您有重复的信息(您不需要x2):

>>> [[x+'/'+y for y in 'ab'] for x in '012']
[['0/a', '0/b'], ['1/a', '1/b'], ['2/a', '2/b']]
    # desire output 0,1,2
    # not [0,0],[1,1],[2,2]

以下是做事的等效方法。在这个比较中,我对发生器和列表之间的主要区别有所区别。

列表形式的笛卡儿产品:

((a,b,c) for a in A for b in B for c in C)
            #SAME AS#
((a,b,c) for (a,b,c) in itertools.product(A,B,C))
            #SAME AS#
for a in A:
    for b in B:
        for c in C:
            yield (a,b,c)

矩阵形式的笛卡尔积:

[[[(a,b,c) for a in A] for b in B] for c in C]
            #SAME AS#
def fC(c):
    def fB(b,c):
        def fA(a,b,c):
            return (a,b,c)   
        yield [f(a,b,c) for a in A]
    yield [fB(b,c) for b in B]
[fC(c) for c in C]
            #SAME AS#
Cs = []
for c in C:
    Bs = []
    for b in B:
        As = []
        for a in A:
            As += [a]
        Bs += [As]
    Cs += [Bs]
return Cs

重复应用列表

的功能
({'z':z} for x in ({'y':y} for y in ({'x':x} for x in 'abc')))
              #SAME AS#
for x in 'abc':
    x2 = {'x':x}
    y2 = {'y':x2}
    z2 = {'z':y2}
    yield z2
              #SAME AS#
def f(x):
    return {'z':{'y':{'x':x}}}
return [f(x) for x in 'abc']     # or map(f,'abc')

答案 1 :(得分:4)

[x.split('/')[0] for x in [a for a in c.split(',')]]

从c ='A / B,C / D,E / F'获得所需的['A','C','E']