我正在尝试创建一个由一组数字的所有变体组成的元组列表。但是,我想从列表中删除所有序列相同但由一个或两个位置偏移的变体。例如:
(-1,1,2)
,(1,2,-1)
和(2,-1,1)
我只想要第一个。
这是我要去的地方
import itertools as it
list = [-1, 0, 1, 2]
cycles = []
list_cycle_3 = it.permutations(cycles, 3)
list_cycle_4 = it.permutations(cycles, 4)
for item in list_cycle_3:
cycles.append(item)
for item in list_cycle_4:
cycles.append(item)
print(cycles)
结果是:
[(-1, 0, 1), (-1, 0, 2), (-1, 1, 0), (-1, 1, 2), (-1, 2, 0), (-1, 2, 1),
(0, -1, 1), (0, -1, 2), (0, 1, -1), (0, 1, 2), (0, 2, -1), (0, 2, 1),
(1, -1, 0), (1, -1, 2), (1, 0, -1), (1, 0, 2), (1, 2, -1), (1, 2, 0),
(2, -1, 0), (2, -1, 1), (2, 0, -1), (2, 0, 1), (2, 1, -1), (2, 1, 0),
(-1, 0, 1, 2), (-1, 0, 2, 1), (-1, 1, 0, 2), (-1, 1, 2, 0), (-1, 2, 0, 1), (-1, 2, 1, 0), (0, -1, 1, 2), (0, -1, 2, 1), (0, 1, -1, 2), (0, 1, 2, -1),
(0, 2, -1, 1), (0, 2, 1, -1), (1, -1, 0, 2), (1, -1, 2, 0), (1, 0, -1, 2),
(1, 0, 2, -1), (1, 2, -1, 0), (1, 2, 0, -1), (2, -1, 0, 1), (2, -1, 1, 0),
(2, 0, -1, 1), (2, 0, 1, -1), (2, 1, -1, 0), (2, 1, 0, -1)]
接下来我该怎么做才能过滤结果,所以只有我想要的结果,
[(-1, 0, 1), (-1, 0, 2), (-1, 1, 0), (-1, 1, 2), (-1, 2, 0), (-1, 2, 1),
(0, 1, 2), (0, 2, 1), (-1, 0, 1, 2), (-1, 0, 2, 1), (-1, 1, 0, 2),
(-1, 1, 2, 0), (-1, 2, 0, 1), (-1, 2, 1, 0)]
如果这有助于简化列表之间的区别,那就是我想要的列表是所有以-1开头的元组以及没有-1的以0开头的元组
答案 0 :(得分:0)
l=[(-1, 0, 1), (-1, 0, 2), (-1, 1, 0), (-1, 1, 2), (-1, 2, 0), (-1, 2, 1),
(0, -1, 1), (0, -1, 2), (0, 1, -1), (0, 1, 2), (0, 2, -1), (0, 2, 1),
(1, -1, 0), (1, -1, 2), (1, 0, -1), (1, 0, 2), (1, 2, -1), (1, 2, 0),
(2, -1, 0), (2, -1, 1), (2, 0, -1), (2, 0, 1), (2, 1, -1), (2, 1, 0),
(-1, 0, 1, 2), (-1, 0, 2, 1), (-1, 1, 0, 2), (-1, 1, 2, 0), (-1, 2, 0, 1), (-1, 2, 1, 0), (0, -1, 1, 2), (0, -1, 2, 1), (0, 1, -1, 2), (0, 1, 2, -1),
(0, 2, -1, 1), (0, 2, 1, -1), (1, -1, 0, 2), (1, -1, 2, 0), (1, 0, -1, 2),
(1, 0, 2, -1), (1, 2, -1, 0), (1, 2, 0, -1), (2, -1, 0, 1), (2, -1, 1, 0),
(2, 0, -1, 1), (2, 0, 1, -1), (2, 1, -1, 0), (2, 1, 0, -1)]
l2=[]
for i in l:
if i[0] == -1 :
l2.append(i)
print(l2)
此代码有效
输出
[(-1, 0, 1), (-1, 0, 2), (-1, 1, 0), (-1, 1, 2), (-1, 2, 0), (-1, 2, 1), (-1, 0, 1, 2), (-1, 0, 2, 1), (-1, 1, 0, 2), (-1, 1, 2, 0), (-1, 2, 0, 1), (-1, 2, 1, 0)]
答案 1 :(得分:0)
从一个不包含您要过滤的数字的列表开始:
例如,您只需要以0开头的那个。那么您的列表就是
l = [-1, 1, 2]
查找所有两个元素排列并根据需要过滤它们。 然后,Ant通过映射结果集将0作为第一个元素添加。
示例:
In [2]: from itertools import permutations
In [3]: l = [-1, 1, 2]
In [4]: p = permutations(l, 2)
In [5]: [(0, *t) for t in p]
Out[5]: [(0, -1, 1), (0, -1, 2), (0, 1, -1), (0, 1, 2), (0, 2, -1), (0, 2, 1)]
您可以对其中没有-1并从0开始(从列表中省略-1和0)的那些对象执行类似的操作,然后将0作为第一个元素添加到结果集项中。
也不要在代码中覆盖保留的关键字:
list = [...] # do not do that