如何排除已经在以前的循环迭代中使用的生成的随机对?

  • 本文关键字:迭代 循环 随机 排除 何排除 python
  • 更新时间 :
  • 英文 :


我试图建立一个循环,其中随机对生成给定列表。本质上,我想用循环创建所有随机对的组合,而不需要替换。这是带有上下文的逻辑:

import numpy as np

x=['apple','cherry','peach','banana']
count=len(x)
interaction=int(count-1) #possible count of matches for a given fruit
matched=[]
for i in range(interaction):
pairs=np.random.choice(x, size=(int(count/2), 2), replace=False)
matched.append(f'Run Number: {i+1}')
matched.append(pairs.tolist())

打印(匹配)

['Run Number: 1', [['cherry', 'peach'], ['banana', 'apple']], 'Run Number: 2', [['banana', 'peach'], ['apple', 'cherry']], 'Run Number: 3', [['peach', 'cherry'], ['banana', 'apple']]]

问题是我想限制生成相同的对。例如,在第一轮中,我们有"cherry"one_answers"peach"对。然而,在第3组中,我们又看到了"peach"one_answers"cherry"对,它们是相同的,只是倒过来而已。

后续迭代如何考虑保存在匹配列表中的先前对,并基于剩余的值生成新的对?

想到的一个可能的解决方案是使用itertools.permutations查找列表中所有可能的元素组合,然后以某种方式过滤掉那些"重复的";元素—例如,您提到(cherry, peach)(peach, cherry)不会被认为是唯一的,因为它们本质上都包含相同的项。因此,一旦我们有了可能的配对,我们就可以过滤掉结果,这样我们最终就只剩下唯一的配对了。

import itertools
from pprint import pprint
x = ['apple', 'cherry', 'peach', 'banana']
# Find the possible combinations of `x` in pairs of two elements each
possible_pairs = list(itertools.permutations(x, 2))
# That'll list you all possible permutations, even ones like
# (apple, peach) and (peach, apple). So, we'll want to filter
# these duplicates out.
# Note: I don't know if there's a better approach, this is just
# the first one that came to mind.
unique_pairs = []
for pair in possible_pairs:
unique_pair = set(pair)
if unique_pair not in unique_pairs:
unique_pairs.append(unique_pair)
pprint(unique_pairs)

输出:

[{'apple', 'cherry'},
{'peach', 'apple'},
{'banana', 'apple'},
{'peach', 'cherry'},
{'banana', 'cherry'},
{'banana', 'peach'}]

更新当然,在Python中总是有更简单的方法来做事情,在这种情况下,我不知道还有更简单的方法。这个答案基本上向我解释了。所以现在我们可以把上面的逻辑归结为:
unique_pairs = list(itertools.combinations(x, 2))

返回与第一次相同的结果。

我在java中做过这种事情,我所做的是创建另一个列表来保存所有添加的项目,然后在添加新项目之前检查它。这样,我只添加没有添加的项,一旦循环结束,我就清除列表以释放内存。

在python中可以使用" In "语句如下:

array = [ a,b,c]
hasitem = a in array
print(hasitem)
#this will display true

所以在你的例子中,现在你需要循环通过对来获得每个项目,并检查列表中存储的已添加的项目,然后只添加不在列表中的项目。

编辑的例子:

x=['apple','cherry','peach','banana']
c=[]
count=len(x)
interaction=int(count-1) #possible count of matches for a given 
fruit
matched=[]
for i in range(interaction):
pairs=np.random.choice(x, size=(int(count/2), 2), 
replace=False)
if pairs.tolist()[i] not in c:
matched.append(f'Run Number: {i+1}')
matched.append(pairs.tolist()[i])
c.append(pairs.tolist()[i])

最新更新