题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
方法一:
import itertools
A = ["a", "b", "c"]
B = ["x", "y", "z"]
rank = [list(each) for each in itertools.permutations(B)] # 将对手的全部组合方式列出来
print("['a', 'b', 'c']分别对应的对手是:", rank[[i[0]!='x' and i[2]!='x' and i[2]!='z' for i in rank].index(True)]) # and for返回的是bool列表,再通过索引True对应好的下标返回rank即可
方法二:其实是一样的
import itertools
A = ["a", "b", "c"]
B = ["x", "y", "z"]
rank = [list(each) for each in itertools.permutations(B)] # 将对手的全部组合方式列出来
print("['a', 'b', 'c']分别对应的对手是:", [i for i in rank if i[0]!='x' and i[2]!='x' and i[2]!='z'][0])
分析语法一:返回bool列表
import itertools
A = ["a", "b", "c"]
B = ["x", "y", "z"]
rank = [list(each) for each in itertools.permutations(B)] # 将对手的全部组合方式列出来
print(rank)
print([i[0]!='x' and i[2]!='x' and i[2]!='z' for i in rank])
[['x', 'y', 'z'], ['x', 'z', 'y'], ['y', 'x', 'z'], ['y', 'z', 'x'], ['z', 'x', 'y'], ['z', 'y', 'x']]
[False, False, False, False, True, False]
分析语法二:直接输出结果
import itertools
A = ["a", "b", "c"]
B = ["x", "y", "z"]
rank = [list(each) for each in itertools.permutations(B)] # 将对手的全部组合方式列出来
print(rank)
print([i for i in rank if i[0]!='x' and i[2]!='x' and i[2]!='z'])
[['x', 'y', 'z'], ['x', 'z', 'y'], ['y', 'x', 'z'], ['y', 'z', 'x'], ['z', 'x', 'y'], ['z', 'y', 'x']]
[['z', 'x', 'y']]