组合后如何找到列表的其余部分

时间:2019-03-23 01:08:24

标签: python

在这种情况下,您能帮我吗? 我有3个清单。

list1 = [ "a", "b", "c", "d"]
list2 = ["x", "y", "z"]
list3 = [1, 2, 3, 4, 5, 6, 7]

首先,我需要获取list1的3个元素,list2的2个元素和list3的4个元素,然后将它们组合起来:

[a, b, c, x, y, 1, 2, 3, 4]
[a, b, c, x, z, 1, 2, 3, 5]
[a, b, c, x, z, 1, 2, 3, 6]
[a, b, c, x, z, 1, 2, 3, 7]
....

然后我需要在末尾打印出list3其余部分的3个元素:

[a, b, c, x, y, 1, 2, 3, 4, 5, 6, 7] 
[a, b, c, x, z, 1, 2, 3, 5, 4, 6, 7]
[a, b, c, x, z, 1, 2, 3, 6, 4, 5, 7]
[a, b, c, x, z, 1, 2, 3, 7, 4, 5, 6]
....

我使用了2个列表的减法,但显示错误

 TypeError: unsupported operand type(s) for -: 'list' and 'itertools.combinations'

...

combi1 = combinations(list1, 3)
combi2 = combinations(list2, 2)
combi3 = combinations(list3, 4)
rest3 = list3 -  combi3
com = product(combi1, combi2, combi3)

请帮助我解决这个问题! 非常感谢!

python

1 个答案:

答案 0 :(得分:0)

您可以使用import ast, inspect import numpy as np import sympy as sp def f(a): return np.array([np.sin(a), np.cos(a)]) def f2(a): return np.array([1, np.sin(a)]) def f3(a): return f(a) + f2(a) translate = {'array': 'Array'} class np_to_sp(ast.NodeTransformer): def visit_Name(self, node): if node.id=='np': node = ast.copy_location(ast.Name(id='sp', ctx=node.ctx), node) return node def visit_Attribute(self, node): self.generic_visit(node) if node.value.id=='sp' and node.attr in translate: fields = {k: getattr(node, k) for k in node._fields} fields['attr'] = translate[node.attr] node = ast.copy_location(ast.Attribute(**fields), node) return node from types import FunctionType for fn in f3.__code__.co_names: fo = globals()[fn] if not isinstance(fo, FunctionType): continue z = ast.parse(inspect.getsource(fo)) np_to_sp().visit(z) exec(compile(z, '', 'exec')) x = sp.Symbol('x') print(f3(x)) 来对[sin(x) + 1, sin(x) + cos(x)] 之后的元组列表进行展平,要获取其余列表,可以使用chain-product(注意,这需要您的list1到list3没有重叠)

set