分享几道很有意思又简单的面试题
a = ['a,1', 'b,3,22', 'c,3,4']
b = ['a,2', 'b,1', 'd,2']
按每个字符串的第一个值,合并a和b到c
效果如下
c = ['a,1,2', 'b,3,22,1', 'c,3,4', 'd,2']
a = ['a,1', 'b,3,22', 'c,3,4']
b = ['a,2', 'b,1', 'd,2']
# 解如下:
def func(a):
dic = dict()
for i in a:
k, v = i.split(',', 1)
dic[k] = v
return dic
a = func(a)
b = func(b)
def func_dic(a: dict, b: dict):
for ka, va in a.items():
if ka in b.keys():
a[ka] = va + ',' + b[ka]
else:
for kb, vb in b.items():
if kb not in a.keys():
a[kb] = vb
return a
a = func_dic(a, b)
c = [k + ',' + v for k, v in a.items()]
print(c)
多层嵌套列表合并 并遍历
A = [1,2,3,[4,5,6,7,[1,2,4,5,6,[12,3,4,5]]]]
A = [1,2,3,[4,5,6,7,[1,2,4,5,6,[12,3,4,5]]]]
lst_A = list()
# 生成器解法
def func(a):
for i in a:
if type(i) == list:
for j in func(i):
yield j
else:
yield i
for x in func(A):
list_A.append(x)
print(x)
# 运用到生成器 很有趣味性哦
# 看似很粗暴的递归解法
def func(A):
for i in A:
if type(i) == list:
func(i)
else:
list_A.append(i)
print(i)
return list_A
func(A)