我有一个列表,如果项目/元组包含这样的集合:
a_list = [(a, {x}), (b, {y}), (c, {y,z}), (d, {y,z}), (e, {x,y}), (f, {x,y,z})]
样本模式:
pattern = {x,y}
给定了一些绘制,我想从a_list生成一系列适合模式的项目。模式应该用元组的第二部分即集合来实现。
示例:
draws = 2
的结果可能是:
result = [(a, {x}), (b, {y})]
# x, y
或
result = [(e, {x,y}), (a, {x})]
# x, y
或
result = [(e, {x,y}), (b, {y})]
# x, y
两种情况都符合2次抽签中的模式{x,y}。
draws = 1
的结果只能是:
result = (e, {x,y})
# x, y
因为只有一个绘图来完成模式,只有项目e完全匹配模式。
draws = 7
的结果可能是:
result = [(a, {x}), (b, {y}), (e, {x,y}), (f, {x,y,z}), (c, {y,z})]
# x, y, x, y, x, y, y
可以完成这样的功能,如果,如何?
感谢您的帮助!
松饼
答案 0 :(得分:0)
如果我从您的问题和您的评论中理解的是正确的,则下面的函数应该为您提供正确的输出/打印,并且应该与您在问题中所期望的相同。
这是我的解决方案
from itertools import groupby
from random import randint
a_list = [('a', {'x'}), ('b', {'y'}), ('c', {'y','z'}), ('d', {'y','z'}), ('e', {'x','y'}), ('f', {'x','y','z'})]
pattern = {'x', 'y'}
def seq_gen(a = [], pattern = set, draws = 0):
single, multi = [], []
for i in a:
if len(i[1]) == 1:
single.append(i)
else:
multi.append(i)
final = [j for j in single if list(pattern)[0] in j[1] or list(pattern)[1] in j[1]]
final += [j for j in multi if pattern == j[1]]
# Debug
#print(final)
if draws == 1:
for i in final:
if len(i[1]) == 2:
# for better use, return a list not a tuple
return "draw(1) => {0}".format([i])
if draws > len(final):
k, f = list(), tuple()
for _, v in groupby(a, lambda x: x[1]):
# Debug
#print(list(v))
k += list(v)[0]
return "draw({0}) => {1}".format(draws, [tuple(k[x:x+2]) for x in range(0,len(k), 2)])
if draws == len(final):
return "draw({0}) => {1}".format(draws, final)
else:
aa = []
while len(aa) != 2:
element = final[randint(0, len(final) -1)]
if element not in aa:
aa.append(element)
return "draw({0}) => {1}".format(draws, aa)
for i in range(1,8):
print(seq_gen(a_list, pattern, i))
输出:
draw(1) => [('e', {'x', 'y'})]
draw(2) => [('e', {'x', 'y'}), ('a', {'x'})]
draw(3) => [('a', {'x'}), ('b', {'y'}), ('e', {'x', 'y'})]
draw(4) => [('a', {'x'}), ('b', {'y'}), ('c', {'z', 'y'}), ('e', {'x', 'y'}), ('f', {'x', 'z', 'y'})]
draw(5) => [('a', {'x'}), ('b', {'y'}), ('c', {'z', 'y'}), ('e', {'x', 'y'}), ('f', {'x', 'z', 'y'})]
draw(6) => [('a', {'x'}), ('b', {'y'}), ('c', {'z', 'y'}), ('e', {'x', 'y'}), ('f', {'x', 'z', 'y'})]
draw(7) => [('a', {'x'}), ('b', {'y'}), ('c', {'z', 'y'}), ('e', {'x', 'y'}), ('f', {'x', 'z', 'y'})]
PS:不要犹豫回复您的反馈意见。如果出现问题,我会尝试使用您的新查询进行修复。