一道Python面试题的几种解答: 两个元祖T1=('a', 'b'), T2=('c', 'd'),请使用匿名函数将其转变成[{'a': 'c'}, {'b': 'd'}]

方法一:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> list(map(lambda x:{x[0]:x[1]}, zip(T1, T2)))
[{'a': 'c'}, {'b': 'd'}]

方法二:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> [{v1:v2} for (i1,v1) in enumerate(T1) for (i2,v2) in enumerate(T2) if i1==i2]
[{'a': 'c'}, {'b': 'd'}]

方法三:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> ret = lambda t1,t2:[{x:y} for x in t1 for y in t2 if t1.index(x) == t2.index(y)]
> ret(T1, T2)
[{'a': 'c'}, {'b': 'd'}]

方法四:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> ret = lambda t1,t2:[{x,y} for (x,y) in zip(t1, t2)]
> ret(T1, T2)
[{'a', 'c'}, {'d', 'b'}]

方法五:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> ret = lambda t1,t2:[{t1[i]:t2[i]} for i in range(len(t1))]
> ret(T1, T2)
[{'a': 'c'}, {'b': 'd'}]

方法六:

> T1 = ('a', 'b')
> T2 = ('c', 'd')
> list(map(lambda x,y:{x:y}, T1, T2))
[{'a': 'c'}, {'b': 'd'}]

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com