如何将列表的每个项目包装到其适当的列表中 [英] How to wrap each item of a list into its proper list
问题描述
我该如何打开一个像这样的列表:
How can I turn a list like:
a = [1, 2, 3, 4, 5]
类似于:
b = [[1], [2], [3], [4], [5]]
我当时正在考虑使用 map
函数,但是那我将a精确映射到哪个函数呢?
I was thinking of using the map
function, but then what function would I exactly map a to?
推荐答案
列表理解对于这种事情很有用.我只是将每个单独的项目放在理解内的列表中.为此,使用map会比较困难.
List comprehension are great for this kinda of thing. I simply put each individual item in a list inside the comprehension. Using map for this would be harder to accomplish.
a = [1, 2, 3, 4, 5]
b = [[i] for i in a]
列表推导是在循环内编写小段代码的简写.在循环某事并创建新列表"中,范例是如此普遍,以至于python决定创建特定的语法来处理这种用法.请注意,还有字典和对类似用法的理解.
List comprehensions are a shorthand for writing small pieces of code inside a loop. The "loop over something and create a new list" paradigm is so common that python decided to create specific syntax to handle this usage. Note that there's also dictionary and set comprehensions for similar usage.
这篇关于如何将列表的每个项目包装到其适当的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!