[英]getting strings and string length from a list into a dictionary
my task was to define a function that takes a list of names and returns a dictionary of names + the corresponding length of each string (Name).我的任务是定义一个函数,该函数接受一个名称列表并返回一个名称字典 + 每个字符串(名称)的相应长度。 The code worked just fine:
代码工作得很好:
def toDict(namelist):
lengths = []
for i in namelist:
lengths.append(len(i))
namedict = dict(zip(namelist, lengths))
return namedict
print(namedict)
However, 2nd part of the task was to do it in one line only and I'm getting stuck a bit there... please help.然而,任务的第二部分是只在一行中完成,我有点卡在那里......请帮忙。
One approach is to use a dict
comprehension:一种方法是使用
dict
理解:
namedict = {name: len(name) for name in namelist}
If you need your entire function definition to be on one line, I'd suggest using a lambda:如果您需要将整个函数定义放在一行上,我建议使用 lambda:
to_dict = lambda name_list: {n: len(n) for n in name_list}
As mentioned in the comments, even though I personally prefer the lambda approach - and though I feel it's a solid use case for it - it's still possible to use a def
and have a normal function on a single line;正如评论中所提到的,尽管我个人更喜欢 lambda 方法 - 尽管我觉得这是一个可靠的用例 - 仍然可以使用
def
并在一行中具有正常功能; you'll just need to put the body immediately after the colon :
as shown below.你只需要在冒号之后立即放置 body
:
如下所示。
def to_dict(name_list): return {n: len(n) for n in name_list}
Another way:其它的办法:
>>> li = ['one', 'three', 'four']
>>> dict(zip(li, map(len, li)))
{'one': 3, 'three': 5, 'four': 4}
How it works:这个怎么运作:
map
applies the function len
to each element in li
map
将函数len
应用于li
每个元素zip
forms a tuple of name and length zip
形成名称和长度的元组dict
takes the tuple and forms a dictionary. dict
接受元组并形成字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.