如果公共密钥具有相同的值,我正在尝试组合n个表(包含dicts的列表)。因此我使用* arg和另外两个表。我的代码工作正常,有两个表但是由于某些未知原因* args什么都不返回。 我的代码:
def join(tbl1, tbl2, *args):
_dic = {}
_list = []
dictsOutOfArgs = []
for d in args:
dictsOutOfArgs.append(d)
for t1, t2 , arg in zip(tbl1, tbl2, dictsOutOfArgs):
for i , j , z in zip(t1, t2, arg):
if i == j == z and t1.get(i) == t2.get(j) == arg.get(z):
_dic = t1.copy()
_dic.update(t2)
_dic.update(arg)
_list.append(_dic)
return _list
if __name__ == '__main__':
import pprint
print(test_answer())
print(test_answer1())
series = [
{'s_id': 'bb', 'title': 'Breaking Bad'},
{'s_id': 'bcs', 'title': 'Better Call Saul'}]
characters = [
{'c_id': 'ww', 'family_name': 'White', 'given_name': 'Walter'},
{'c_id': 'sw', 'family_name': 'White', 'given_name': 'Skyler'},
{'c_id': 'sg', 'family_name': 'Goodman', 'given_name': 'Saul'}]
series_characters = [
{'c_id': 'ww', 's_id': 'bb'},
{'c_id': 'sw', 's_id': 'bb'},
{'c_id': 'sg', 's_id': 'bb'},
{'c_id': 'sg', 's_id': 'bcs'}]
x = join(series_characters, series, characters)
pprint.pprint(x)
预期产出:
[{'c_id': 'ww',
'family_name': 'White',
'given_name': 'Walter',
's_id': 'bb',
'title': 'Breaking Bad'},
{'c_id': 'sw',
'family_name': 'White',
'given_name': 'Skyler',
's_id': 'bb',
'title': 'Breaking Bad'},
{'c_id': 'sg',
'family_name': 'Goodman',
'given_name': 'Saul',
's_id': 'bb',
'title': 'Breaking Bad'},
{'c_id': 'sg',
'family_name': 'Goodman',
'given_name': 'Saul',
's_id': 'bcs',
'title': 'Better Call Saul'}]
返回是:[] 我认为原因是argss没有任何值,所以if条件返回false。
任何想法?
答案 0 :(得分:1)
也许这样的事情(注意它对表的顺序有点挑剔):
def join(tbl1, *args):
ret_list = []
for obj in tbl1:
consolidated = obj.copy()
for join_tbl in args:
keys = consolidated.viewkeys() & join_tbl[0].viewkeys()
match_obj = next(o for o in join_tbl if all(consolidated.get(k) == o.get(k) for k in keys))
if match_obj:
consolidated.update(match_obj)
ret_list.append(consolidated)
return ret_list
join(series_characters, series, characters)
返回
{'c_id': 'ww', 'given_name': 'Walter', 'title': 'Breaking Bad', 's_id': 'bb', 'family_name': 'White'}
{'c_id': 'sw', 'given_name': 'Skyler', 'title': 'Breaking Bad', 's_id': 'bb', 'family_name': 'White'}
{'c_id': 'sg', 'given_name': 'Saul', 'title': 'Breaking Bad', 's_id': 'bb', 'family_name': 'Goodman'}
{'c_id': 'sg', 'given_name': 'Saul', 'title': 'Better Call Saul', 's_id': 'bcs', 'family_name': 'Goodman'}