python - Itertools permutation with lambda -
items = ['a', 'b', 'c','d'] itertools import permutations p in permutations(items): p1=(''.join(p)) p2=filter(lambda x: x[1]=='b',p1) i want exclude strings b on second index. when try print filter object
<filter @ 0x7f8d729ba908> p in p2: print (p) indexerror traceback (most recent call last) <ipython-input-27-fbcaa516953f> in <module>() ----> 1 p in p2: 2 print (p) <ipython-input-23-c6289753f791> in <lambda>(x) 1 p in permutations(items): 2 p1=(''.join(p)) ----> 3 p2=filter(lambda x: x[1]=='b',p1) indexerror: string index out of range is lambda right choice this?why have string index problem?
each p one permutation. p2 1 string. if filter it, lambda function being applied each character in string. x[1] out of range.
perhaps mean this:
strings = [''.join(p) p in permutations(items)] strings = filter(lambda x: x[1]!='b', strings) or more simply
strings = [''.join(p) p in permutations(items) if p[1]!='b'] (using condition p[1]!='b' include permutations second character not 'b')
Comments
Post a Comment