如题:
A = [
'a,1',
'bb,3,22',
'c,3,4',
'b,5'
]
B = [
'a,2',
'bb,1',
'd,2',
'a,3'
]
现要求合并A和B到C,输出C为:
['a,1,2,3', 'bb,3,22,1', 'c,3,4', 'b,5', 'd,2']
即A中'a', 'bb', 'c', 'b'等作为参考,同B一样合并为一个数组。
当A和B包含的元素很多时,要注意效率。能否以O(n)的时间复杂度来实现呢?可以想一想再看答案。
。。。不排版了,一把嗦。
from collections import defaultdict
def append_val(list_A: list, list_B: list) -> list:
list_C = []
dic = defaultdict(str)
for i in list_A, list_B:
for val in i:
first_index = val.index(',')
key = val[:first_index]
value = val[first_index + 1:]
if dic[key] == '':
dic[key] = value
continue
dic[key] = dic[key] + ',' + value
for k, v in dic.items():
list_C.append(k + ',' + v)
return list_C