如何从python中的列表生成唯一数组?
假设我有一个简单的python列表:如何从python中的列表生成唯一数组?,python,numpy,Python,Numpy,假设我有一个简单的python列表: a = [0,1,2] 如何从该列表生成唯一数组,以便获得: arr_gen = [[0,1], [1,2], [0,2]] 我尝试过使用numpy.random.choice,方法如下: >>> np.random.choice(a, (3,2), replace = False) 但我得到以下错误: >>> ValueError: Cannot take a large
a = [0,1,2]
如何从该列表生成唯一数组,以便获得:
arr_gen = [[0,1],
[1,2],
[0,2]]
我尝试过使用numpy.random.choice,方法如下:
>>> np.random.choice(a, (3,2), replace = False)
但我得到以下错误:
>>> ValueError: Cannot take a larger sample than population when 'replace=False'
您可以尝试使用内置的
itertools
模块
导入itertools
>>>a=[0,1,2]
>>>列表(itertools.组合(a,2)
[(0, 1), (0, 2), (1, 2)]
您可以尝试使用内置的
itertools
模块
导入itertools
>>>a=[0,1,2]
>>>列表(itertools.组合(a,2)
[(0, 1), (0, 2), (1, 2)]
您也可以通过使用
iterations
和numpy
解决此问题,而无需使用itertools
import numpy
def combinations(iterable, r):
char = tuple(iterable)
n = len(char)
if r > n:
return
index = numpy.arange(r)
# retruns the first sequence
yield tuple(char[i] for i in index)
while True:
for i in reversed(range(r)):
if index[i] != i + n - r:
break
else:
return
index[i] += 1
for j in range(i + 1, r):
index[j] = index[j-1] + 1
yield tuple(char[i] for i in index)
a = [0, 1, 2]
print([x for x in combinations(a, 2)])
输出:
[(0, 1), (0, 2), (1, 2)]
您也可以通过使用
itertools
和numpy
来解决此问题,而无需使用itertools
import numpy
def combinations(iterable, r):
char = tuple(iterable)
n = len(char)
if r > n:
return
index = numpy.arange(r)
# retruns the first sequence
yield tuple(char[i] for i in index)
while True:
for i in reversed(range(r)):
if index[i] != i + n - r:
break
else:
return
index[i] += 1
for j in range(i + 1, r):
index[j] = index[j-1] + 1
yield tuple(char[i] for i in index)
a = [0, 1, 2]
print([x for x in combinations(a, 2)])
输出:
[(0, 1), (0, 2), (1, 2)]
方法1 只需从python中的itertools模块导入组合,就可以得到想要的
>>> from itertools import combinations
>>> print(list(map(list,combinations([0, 1, 2], 2))))
[[0, 1], [0, 2], [1, 2]]
方法2(获取唯一列表)
在这个问题中,您还说您还需要生成唯一的数组,所以让我们假设您的数组是[0,1,1]。您可以使用这个数组
>>> from itertools import combinations
>>> print(list(map(list,{*map(tuple,combinations([0, 1, 2], 2))})))
[[0, 1], [1, 1]]
在集合中删除重复项。因此,在此之后,您还必须将集合转换为列表
方法3(递归方法)
方法1 只需从python中的itertools模块导入组合,就可以得到想要的
>>> from itertools import combinations
>>> print(list(map(list,combinations([0, 1, 2], 2))))
[[0, 1], [0, 2], [1, 2]]
方法2(获取唯一列表)
在这个问题中,您还说您还需要生成唯一的数组,所以让我们假设您的数组是[0,1,1]。您可以使用这个数组
>>> from itertools import combinations
>>> print(list(map(list,{*map(tuple,combinations([0, 1, 2], 2))})))
[[0, 1], [1, 1]]
在集合中删除重复项。因此,在此之后,您还必须将集合转换为列表
方法3(递归方法)