提取集合中的元组
Extracting tuples in a set
我有这个样本集:{(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}.
现在我需要删除包含一些特定数字的元组。例如:从这个集合中,删除包含 [4,5] 的元组,因此输出应该是这样的:样本的 {(1, 3, 3), (2, 2, 3)}。
我用这段代码找到了所有组合,但我现在卡住了。
def compositions(k, n):
if n==0:
return []
if k == 1:
return [(n,)]
comp = []
for i in range(n + 1):
for t in compositions(k - 1, n - i):
if i>0:
comp.append((i,) + t)
return set(comp)
compositions(3, 7)
我该怎么做?
非常感谢您。
这可以通过 one-liner 来完成。
your_set = {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}
your_set = {ele for ele in your_set if all(x not in ele for x in [4, 5])}
print(your_set)
打印:
{(2, 2, 3), (1, 3, 3)}
def extract(array, filter):
res = []
for i in array:
flag = 1
for j in filter:
if j in i:
flag = 0
break
if flag:
res.append(i)
return res
print(
extract(
[(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)],
[4,5]
)
)
你可以试试这个。
我有这个样本集:{(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}.
现在我需要删除包含一些特定数字的元组。例如:从这个集合中,删除包含 [4,5] 的元组,因此输出应该是这样的:样本的 {(1, 3, 3), (2, 2, 3)}。
我用这段代码找到了所有组合,但我现在卡住了。
def compositions(k, n):
if n==0:
return []
if k == 1:
return [(n,)]
comp = []
for i in range(n + 1):
for t in compositions(k - 1, n - i):
if i>0:
comp.append((i,) + t)
return set(comp)
compositions(3, 7)
我该怎么做?
非常感谢您。
这可以通过 one-liner 来完成。
your_set = {(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)}
your_set = {ele for ele in your_set if all(x not in ele for x in [4, 5])}
print(your_set)
打印:
{(2, 2, 3), (1, 3, 3)}
def extract(array, filter):
res = []
for i in array:
flag = 1
for j in filter:
if j in i:
flag = 0
break
if flag:
res.append(i)
return res
print(
extract(
[(1, 1, 5), (1, 2, 4), (1, 3, 3), (1, 4, 2), (1, 5, 1), (2, 1, 4), (2, 2, 3)],
[4,5]
)
)
你可以试试这个。