一道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'}]
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。