我正在努力在 python 中实现自然连接。前两行显示表的属性,接下来的两行显示每个表的元组或行。
预期输出:
[['A', 1, 'A', 'a', 'A'],
['A', 1, 'A', 'a', 'Y'],
['A', 1, 'Y', 'a', 'A'],
['A', 1, 'Y', 'a', 'Y'],
['S', 2, 'B', 'b', 'S']]
我得到了什么:
[['A', 1, 'A', 'a', 'A', 'Y'],
['A', 1, 'A', 'a', 'A', 'Y']]
我查看了代码,一切似乎都是正确的,我将不胜感激。
t1atts = ('A', 'B', 'C', 'D')
t2atts = ('B', 'D', 'E')
t1tuples = [['A', 1, 'A', 'a'],
['B', 2, 'Y', 'a'],
['Y', 4, 'B', 'b'],
['A', 1, 'Y', 'a'],
['S', 2, 'B', 'b']]
t2tuples = [[1, 'a', 'A'],
[3, 'a', 'B'],
[1, 'a', 'Y'],
[2, 'b', 'S'],
[3, 'b', 'E']]
def findindices(t1atts, t2atts):
t1index=[]
t2index=[]
for index, att in enumerate(t1atts):
for index2, att2 in enumerate(t2atts):
if att == att2:
t1index.append(index)
t2index.append(index2)
return t1index, t2index
def main():
tpl=0; tpl2=0; i=0; j=0; count=0; result=[]
t1index, t2index = findindices(t1atts, t2atts)
for tpl in t1tuples:
while tpl2 in range(len(t2tuples)):
i=0; j=0
while (i in range(len(t1index))) and (j in range(len(t2index))):
if tpl[t1index[i]] != t2tuples[tpl2][t2index[j]]:
i=len(t1index)
j=len(t1index)
else:
count+=1
i+=1
j+=1
if count == len(t1index):
extravals = [val for index, val in enumerate(t2tuples[tpl2]) if index not in t2index]
temp = tpl
tpl += extravals
result.append(tpl)
tpl = temp
count=0
tpl2+=1
print result