Rearrange Itertools with Lambda

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) 

I want to exclude rows with b in the second index. When I try to print a filter object

 <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 

Is lambda the right choice for this? Why am I having a row index problem?

+5
source share
2 answers

Each p is one permutation. So p2 is one line. If you filter it, your lambda function is applied to each character in the string. Thus, x[1] out of range.

Perhaps you mean something like this:

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

or more simply

 strings = [''.join(p) for p in permutations(items) if p[1]!='b'] 

(Using condition p[1]!='b' to include only permutations where the second character is not 'b' )

+8
source

filter fine, but you have to apply it outside the loop. The problem with your code is that you are passing the string to filter , so str ing is treated as iterative and repeated one character at a time. Since the character is a string of size 1, x[1] guaranteed beyond the bounds.

Try the following:

 from itertools import permutations perms = list(filter(lambda x: x[1] != 'b', permutations(items))) # remove list(..) if you're using python2 

If you need a list of lines, you can use map :

 perms = list(map(''.join, filter(lambda x: x[1] != 'b', permutations(items)))) 

Or, as a list comprehension:

 perms = [''.join(p) for p in permutations(items) if p[1] != 'b'] 

If you want to print it as you create it, use a loop instead:

 for p in permutations(items): if p[1] != 'b': print(''.join(p)) 

In addition, the filter condition includes elements in which the condition is true, so your condition needs a little modification if you want to exclude lines whose first character is b (you will need x[1] != b , not x[1] == b )

+10
source

Source: https://habr.com/ru/post/1271048/


All Articles