nac*_*hmr 10 python tuples list
经过大量搜索没有成功,我需要帮助.
我有一个元组列表列表.列表列表中的每个列表代表我系统中的特定数量的公式.此列表中的任何元素都是一个元组,表示元素的类型(变量,参数,常量,操作...)和元素的名称.例如,对于公式x1 + x2 + A1,x1-x3和sin(x2)+ A1,我们将:
[
[('VAR', 'x1'), ('PLUS', '+'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')],
[('VAR', 'x1'), ('LESS', '-'), ('VAR', 'x3')],
[('SIN', 'sin'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')]
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试确定每个变量出现在哪个公式中.在上面的例子中,我认为x1变量是1和2公式,x2变量是1和3公式,x3是2公式,所以我的输出将是这样的:
[
['x1', 1, 2],
['x2', 1, 3],
['x3', 2],
]
Run Code Online (Sandbox Code Playgroud)
目前我的代码非常低效,根本不起作用,但这里是:
cont = 0
for subL1 in L:
for subL2 in L:
if len(subL1) != 1 and len(subL2) != 1:
if subL1 != subL2 and subL2:
for x,y in subL1:
for z,t in subL2:
if ( x == 'VAR'
and z == 'VAR'
and y == t
):
print "Variable", y , "repeated"
else:
print "list with 1 lenght\n"
subL1.pop(0)
cont = cont + 1
Run Code Online (Sandbox Code Playgroud)
MSe*_*ert 15
您可以使用a collections.defaultdict来存储每个变量的公式(实际上是列表列表中的索引):
from collections import defaultdict
dd = defaultdict(set) # use a set as factory so we don't keep duplicates
for idx, subl in enumerate(l, 1): # iterate over the sublists with index starting at 1
for subt in subl: # iterate over each tuple in each sublist
label, val = subt # unpack the tuple
if label == 'VAR': # if it's a VAR save the index in the defaultdict
dd[val].add(idx)
Run Code Online (Sandbox Code Playgroud)
例如:
l = [[('VAR', 'x1'), ('PLUS', '+'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')],
[('VAR', 'x1'), ('LESS', '-'), ('VAR', 'x3')],
[('SIN', 'sin'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')]
]
Run Code Online (Sandbox Code Playgroud)
它给:
print(dd)
# defaultdict(set, {'x1': {1, 2}, 'x2': {1, 3}, 'x3': {2}})
Run Code Online (Sandbox Code Playgroud)
要获得所需的输出,您只需将其再次转换为列表,例如(仅限python-3.x):
>>> [[name, *sorted(formulas)] for name, formulas in sorted(dd.items())]
[['x1', 1, 2], ['x2', 1, 3], ['x3', 2]]
Run Code Online (Sandbox Code Playgroud)
formula = [
[('VAR', 'x1'), ('PLUS', '+'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')],
[('VAR', 'x1'), ('LESS', '-'), ('VAR', 'x3')],
[('SIN', 'sin'), ('VAR', 'x2'), ('PLUS', '+'), ('PAR', 'A1')]
]
variables = collections.defaultdict(set)
for line_no, line in enumerate(formula):
for typ, value in line:
if typ == 'VAR':
variables[value].add(line_no)
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)variablesdefaultdict(set,{'x1':{0,1},'x2':{0,2},'x3':{1}})