Python 3.x 循环遍历列表并在函数内返回列表
我试图返回一个列表,返回时得到的结果不同Python 3.x 循环遍历列表并在函数内返回列表,python-3.x,list,dictionary,Python 3.x,List,Dictionary,我试图返回一个列表,返回时得到的结果不同 def list_book(): lines = [['eofih', 'sdf', 'False'], ['sfdds', 'afds', 'False']] books = [{"name": line[0], "author": line[1], "read": line[2]} for line in lines ] return boo
def list_book():
lines = [['eofih', 'sdf', 'False'], ['sfdds', 'afds', 'False']]
books = [{"name": line[0], "author": line[1], "read": line[2]}
for line in lines
]
return books
这是完美的回报:
[{'name': 'eofih', 'author': 'sdf', 'read': 'False'},{'name': 'sfdds', 'author': 'afds', 'read': 'False'}]
但当我尝试做以下事情时:
def list_book():
lines = [['eofih', 'sdf', 'False'], ['sfdds', 'afds', 'False']]
for line in lines:
books = [{"name": line[0], "author": line[1], "read": line[2]}]
return books
此操作仅返回列表中的最后一项:
[{'name': 'sfdds', 'author': 'afds', 'read': 'False'}]
请告诉我是否可以在第二个选项中返回整个列表。第一个代码有什么问题?如果你已经知道它是你想要的,为什么不使用它呢?答案基本上是“将其更改为第一个代码”。
def list_book():
lines = [['eofih', 'sdf', 'False'], ['sfdds', 'afds', 'False']]
books = []
for line in lines:
books += [{"name": line[0], "author": line[1], "read": line[2]}]
return books