返回f字符串的For循环函数 [英] For loop function that returns f-string
问题描述
我是python的新手,正在尝试编写一个函数,该函数接受字典列表,并返回一个新的字符串列表,其中包含串联的每个字典中的名字和姓氏键.
I am new to python and trying to write a function that accepts a list of dictionaries and returns a new list of strings with the first and last name keys in each dictionary concatenated.
names = [{'first': 'John', 'last': 'Smith'}, {'first': 'Jessie', 'last': 'Snow'}]
def name_function(lst):
for name in lst:
return f"{name['first']} {name['last']}"
names_function(names)
'John Smith'
我编写了一个for循环,该循环遍历字典列表并返回一个f字符串,该字符串将每个字典中的名字和姓氏键连接在一起,但是,该循环无法在第一个键之外进行迭代,我希望有人可以指出我的问题.
I wrote a for loop that iterates thru the list of dictionaries and returns an f-string that concatenates first and last name keys in each dictionary, however, the loop fails to iterate beyond the first key and I am hoping some one can point me to the issue.
推荐答案
虽然有一个循环,但在循环中也有一个 return
.在列表的第一次迭代中,此 return
将被命中并且函数的执行将在那里停止,仅返回该行的值(即字符串),而不是预期的列表.
While you have a loop, you also have a return
inside the loop. On the first iteration of the list this return
will be hit and execution of the function will stop there, returning only value on that line — which is a string — rather than the list intended.
您要么需要在函数中添加一个列表以用作累加器,然后再返回—
You either need to add a list to the function to use as an accumulator before returning —
def names_function(lst):
names = []
for name in lst:
names.append(f"{name['first']} {name['last']}")
return names
或者使用列表理解
def names_function(lst):
return [f"{name['first']} {name['last']}" for name in lst]
names_function(names)
两者都会输出
['John Smith', 'Jessie Snow']
您还可以将 return
替换为 yield
,以将其转换为生成器.要获取所有值,您需要迭代生成器(或在其上调用 list
)
You could also replace the return
with a yield
to turn this into a generator. To get all the values you would need to iterate the generator (or call list
on it)
def names_function(lst):
for name in lst:
yield f"{name['first']} {name['last']}"
list(names_function(names))
哪个给出相同的结果
['John Smith', 'Jessie Snow']
这篇关于返回f字符串的For循环函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!