两个元祖T1=('a', 'b'),T2=('c', 'd')使用匿名函数将其转变成[{'a': 'c'},{'b': 'd'}]的几种方法

yipeiwu_com6年前Python基础

一道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'}]

总结

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

相关文章

Pytoch之torchvision.transforms图像变换实例

transforms.CenterCrop(size) 将给定的PIL.Image进行中心切割,得到给定的size,size可以是tuple,(target_height, target...

Python pickle模块实现对象序列化

这篇文章主要介绍了Python pickle模块实现对象序列化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 作用 对Python对...

python实现对csv文件的列的内容读取

以下代码测试在python2.7 mac上运行成功 import csv with open('/Users/wangzhao/Downloads/test.csv', 'U')...

Python BS4库的安装与使用详解

Python BS4库的安装与使用详解

Beautiful Soup 库一般被称为bs4库,支持Python3,是我们写爬虫非常好的第三方库。因用起来十分的简便流畅。所以也被人叫做“美味汤”。目前bs4库的最新版本是4.60。...

python+matplotlib实现礼盒柱状图实例代码

python+matplotlib实现礼盒柱状图实例代码

演示结果: 完整代码: import matplotlib.pyplot as plt import numpy as np from matplotlib.image impor...