【发布时间】:2021-12-30 21:31:05
【问题描述】:
在一行中实现,使用 lambda 表达式(map/filter/reduce), 获取不同类型列表并返回具有以下键的字典的函数: {‘c’: , ‘i’: , ‘f’: , ‘o’: }
'c' 将显示字符列表 'i' 整数列表 'f' 浮点数列表 'o' 任何其他类型的列表
例如列表: myList = ['a', 2, 3, 's', 2.23]
输出将是: {'c': ['a', 's'], 'i': [2, 3], 'f': [2.23], 'o': []}
到目前为止,我已经制作了一种可行的方法,但我需要以某种方式更改它的一行代码:
def q1a(myList):
myDict = dict.fromkeys(('c', 'i', 'f', 'o'))
myDict['c'] = list(filter(lambda x: type(x) is str, myList))
myDict['i'] = list(filter(lambda x: type(x) is int, myList))
myDict['f'] = list(filter(lambda x: type(x) is float, myList))
myDict['o'] = list(filter(lambda x: type(x) is not float and type(x) is not int and type(x) is not str, myList))
return myDict
【问题讨论】:
-
并不是所有的东西都应该简化为 Python 中的功能单行。使用无聊的
for循环可以更好地完成此操作,该循环一次更新dict一个值。如果我必须在一行中执行此操作,我将使用itertools.groupby和一个函数,该函数接受一个值并返回该值类型的单字母“类别”。
标签: python list dictionary filter lambda