简体   繁体   English

使用 Python3 itertools 排列:如何指定所有 r > 1

[英]Using Python3 itertools permutations: how can I specify all r > 1

I only want the permutations of a string that are of size 2 or more, so no empty set or set of one character.我只想要大小为 2 或更大的字符串的排列,所以没有空集或一个字符集。 It seems r must be an int and I cannot say r = range(2,N) or r>=2 .似乎r必须是 int 并且我不能说r = range(2,N)r>=2 The only solution I can think of is a for-loop;我能想到的唯一解决方案是 for 循环; is there a better way?有没有更好的办法?

You do need a for loop.你确实需要一个for循环。 But you could do it more succinctly with itertools.chain , which would create a generator that yields first all permutations of length 2, then 3, etc.但是您可以使用itertools.chain更简洁地完成它,这将创建一个生成器,该生成器首先生成长度为 2、然后为 3 等的所有排列。

from itertools import chain, permutations

lst = [1, 2, 3]
tuples_gen = chain(*(permutations(lst, i) for i in range(2, len(lst) + 1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM