Python 如何将以下三个列表分为7组?
我试图将A、B和C中的元素分开。我尝试使用if-else,但它似乎有点硬编码Python 如何将以下三个列表分为7组?,python,list,dictionary,Python,List,Dictionary,我试图将A、B和C中的元素分开。我尝试使用if-else,但它似乎有点硬编码 A = ["a","b","c","d"] B = ["a","c","g","e"] C = ["a","b","f","e"] X = [[]*7] common = set(A+B+C) common1 = set(A) & set(B) & set(C) common2 = set(A) & set(B) common3 = set(A) & set(C) common4 = s
A = ["a","b","c","d"]
B = ["a","c","g","e"]
C = ["a","b","f","e"]
X = [[]*7]
common = set(A+B+C)
common1 = set(A) & set(B) & set(C)
common2 = set(A) & set(B)
common3 = set(A) & set(C)
common4 = set(C) & set(B)
for e in common:
if e in common1:
X[0] += e
elif e in common2:
X[1] += e
elif e in common3:
X[2] += e
elif e in common4:
X[3] += e
elif e in A:
X[4] += e
elif e in B:
X[5] += e
else:
X[6] += e
X[0] should contain elements common in A,B,C
X[1] should contain elements common in A,B.
X[2] should contain elements common in A,C.
X[3] should contain elements common in C,B.
X[4] should contain elements common in A.
X[5] should contain elements common in B.
X[6] should contain elements common in C.
最好在字典中完成吗?不是很好的代码,但做了您想要的:
from itertools import combinations
from operator import and_
from functools import reduce
A = ["a", "b", "c", "d"]
B = ["a", "c", "g", "e"]
C = ["a", "b", "f", "e"]
lst = (set(A), set(B), set(C))
ret = []
for r in range(3, 0, -1):
for comb in combinations(lst, r=r):
ret.append(reduce(and_, comb))
print(ret)
我把你的列表转换成了集合<代码>集合a和集合b(
分别添加(集合a和集合b)
)选择两个集合中的项目itertools.combinations
调用r=3
,r=2
和r=1
按您需要的顺序选择组合。我将使用集合和set.intersection
:
A = set(["a","b","c","d"])
B = set(["a","c","g","e"])
C = set(["a","b","f","e"])
X = [
list(A.intersection(B,C)),
list(A.intersection(B)),
list(A.intersection(C)),
list(B.intersection(C)),
list(A),
list(B),
list(C)]
不像@hiro的代码那样可扩展,但一眼就能看出它在做什么。看看这里:当询问家庭作业时(1)注意你的学校政策:在这里寻求帮助可能构成作弊。(2) 指定问题是家庭作业。(3) 首先,真诚地尝试自己解决问题(在问题中包含代码)。(4) 询问现有实施中的具体问题;看见还有,是关于问家庭作业问题的指导。@hiro主角你说得对!X=[集合(A)&集合(B)&集合(C),集合(A)&集合(B),集合(A)&集合(C),集合(C)&集合(B),集合(A),集合(B),集合(C)]组合使用得很好@Ruzihm谢谢。另一方面:以奇怪的方式(或数据结构)排列结果。。。