如何从Python的嵌套列表中删除列表?
我正在使用Python探索概率,我想解决此类问题。我有5对夫妇,从这些夫妻中,我想提取每组三组,而这不包含一对已婚夫妇的人。
import itertools as it
married_couples = [["Mary","John"],["Homer","Marge"],["Beauty","Beast"],["Abigail","George"],["Marco","Luisa"]]
all_persons = []
for couples in married_couples:
for person in couples:
all_persons.append(person)
sample_space = list(it.combinations(all_persons,3))
# Better solution with generator:
sample_space = [s for t in it.combinations(married_couples, 3) for s in it.product(*t)]
现在,我想从样本空间中排除所有包含同一对已婚夫妇的人的结果,我尝试:
correct_results = sample_space.copy()
for couple in married_couples:
for res in sample_space:
if couple[0] in res and couple[1] in res:
if res in correct_results:
correct_results.remove(res)
编辑:我还编辑并将生成器解决方案放入其中,因此您可以将此代码用于目的
I'm exploring probability with the use of python and I want to resolve this kind of problem. I have 5 couples and from these couples, I want to extract each group of three, that doesn't contain persons from a married couple.
import itertools as it
married_couples = [["Mary","John"],["Homer","Marge"],["Beauty","Beast"],["Abigail","George"],["Marco","Luisa"]]
all_persons = []
for couples in married_couples:
for person in couples:
all_persons.append(person)
sample_space = list(it.combinations(all_persons,3))
# Better solution with generator:
sample_space = [s for t in it.combinations(married_couples, 3) for s in it.product(*t)]
Now I would like to proceed excluding from the sample space all results that contains people from the same married couple and I try:
correct_results = sample_space.copy()
for couple in married_couples:
for res in sample_space:
if couple[0] in res and couple[1] in res:
if res in correct_results:
correct_results.remove(res)
Edit: I edited and put also the generator solution inside, so you can use this code for the purpose
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题之所以出现,
是因为它测试这对夫妇在
res
中,而是这对夫妇的第一个元素不是null,第二个元素在res
中。您应该使用:
The problem is in
because it tests not that the couple is in
res
, but that the first element of the couple is not null and the second is inres
.You should use:
这是一种更有效的方法:
如果您只需要迭代此操作,而不需要它作为实际扩展列表,那么您可以创建一个生成器:
然后您可以这样做:
两种解决方案都可以如下:有两个级别。在顶级,它调用
itertools.combinations(已婚_couples,3)
。这产生了原始已婚夫妇的所有三胞胎。然后,对于每个三重态,它使用iterrools.product(*t)
生成所有8个组合,这些组合从三重线中的三对中获取一个组合。Here's a much more efficient way to do this:
If you just need to iterate over this, and don't need it as an actual expanded list, then you can instead create a generator:
Then you can do:
Both solutions work as follows: There are two levels to it. At the top level, it calls
itertools.combinations(married_couples, 3)
. This generates all triplets from the original set of married couples. Then, for each triplet, it usesiterrools.product(*t)
to generate all 8 combinations that take one from each of the three pairs in the triplet.