Python 带lambda的Itertools置换

Python 带lambda的Itertools置换,python,python-3.x,lambda,itertools,Python,Python 3.x,Lambda,Itertools,我想排除第二个索引中带有b的字符串。 当我尝试打印过滤器对象时 items = ['a', 'b', 'c','d'] from itertools import permutations for p in permutations(items): p1=(''.join(p)) p2=filter(lambda x: x[1]=='b',p1) 对于p2中的p: 印刷品(p) 索引器回溯(最后一次最近调用) 在() ---->p2中的p为1: 2份印刷品(p) in(x)

我想排除第二个索引中带有b的字符串。 当我尝试打印过滤器对象时

items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
    p1=(''.join(p))
    p2=filter(lambda x: x[1]=='b',p1)

对于p2中的p:
印刷品(p)
索引器回溯(最后一次最近调用)
在()
---->p2中的p为1:
2份印刷品(p)
in(x)
1表示排列中的p(项目):
2 p1=(''.join(p))
---->3 p2=滤波器(λx:x[1]='b',p1)
索引器错误:字符串索引超出范围

lambda是正确的选择吗?为什么我有字符串索引问题?

filter
很好,但您必须在循环之外应用它。代码的问题在于,您正在将字符串传递给
filter
,因此
str
ing被视为一个iterable,并一次迭代一个字符。由于字符是大小为1的字符串,
x[1]
保证超出范围

试试这个:

<filter at 0x7f8d729ba908>
for p in p2:
    print (p)

IndexError                                Traceback (most recent call last)
<ipython-input-27-fbcaa516953f> in <module>()
----> 1 for p in p2:
      2     print (p)

<ipython-input-23-c6289753f791> in <lambda>(x)
      1 for p in permutations(items):
      2     p1=(''.join(p))
----> 3     p2=filter(lambda x: x[1]=='b',p1)

IndexError: string index out of range
如果需要字符串列表,可以应用
映射

from itertools import permutations
perms = list(filter(lambda x: x[1] != 'b', permutations(items))) # remove list(..) if you're using python2
或者,作为列表理解:

perms = list(map(''.join, filter(lambda x: x[1] != 'b', permutations(items))))
如果要在生成时将其打印出来,请改用循环:

perms = [''.join(p) for p in permutations(items) if p[1] != 'b']
另外,
filter
条件包括条件为true的项,因此如果要排除第一个字符为
b
的字符串,则需要对条件进行轻微修改(您需要
x[1]!=b
,而不是
x[1]==b
)。

每个
p
都是一个排列。因此,
p2
是一个字符串。如果对其进行过滤,lambda函数将应用于字符串中的每个字符。因此
x[1]
超出范围

也许你的意思是这样的:

for p in permutations(items):
    if p[1] != 'b':
        print(''.join(p))
或者更简单地说

strings = [''.join(p) for p in permutations(items)]
strings = filter(lambda x: x[1]!='b', strings)

(使用条件
p[1]!='b'
仅包括第二个字符不是
'b'
的排列)

注意,假设OP在python2上,则无需使用python2@DanielSanchez中的筛选器调用列表,您是对的。@cᴏʟᴅsᴘᴇᴇᴅ 你为什么坚持要创建一个列表?@cᴏʟᴅsᴘᴇᴇᴅ 嗯,不,你不明白我的意思,也没修好。你仍然坚持创建一个列表,现在甚至比以前更多。为什么?问题并不要求它,p2:print(p)中显示的p用例
也不需要它。@StefanPochmann好的。我想在回答中传达的主要内容是OP做错了什么,以及如何修复它。创建列表(或缺少列表)是次要的。
strings = [''.join(p) for p in permutations(items) if p[1]!='b']