Python:对二维数组(列表的列表)中的元素执行操作的单行?
我有一个列表列表,每个列表包含不同数量的字符串。我想(有效地)将这些全部转换为整数,但感觉有点密集,因为我无法让它在我的一生中发挥作用。我一直在尝试: newVals = [int(x) for x in [row for rows in values]]
其中“values”是列表的列表。它一直说 x 是一个列表,因此不能作为 int() 的参数。显然我在这里做了一些愚蠢的事情,那是什么?对于这种事情有一个公认的习语吗?
I have a list of lists, each containing a different number of strings. I'd like to (efficiently) convert these all to ints, but am feeling kind of dense, since I can't get it to work out for the life of me. I've been trying:
newVals = [int(x) for x in [row for rows in values]]
Where 'values' is the list of lists. It keeps saying that x is a list and can therefore not be the argument if int(). Obviously I'm doing something stupid here, what is it? Is there an accepted idiom for this sort of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这使得整数嵌套起来。
如果你想让它们扁平化,这对于 Python3
map()
返回一个迭代器来说也不难。您可以使用
,但在这种情况下您可能更喜欢使用嵌套 LC
This leaves the ints nested
If you want them flattened, that's not hard either
for Python3
map()
returns an iterator. You could usebut you may prefer to use the nested LC's in that case
怎么样:
How about:
另一种解决方法
Another workaround
您只需使用不正确的顺序和括号 - 应该是:
或者如果您需要输出列表,则:
You simply use incorrect order and parenthesis - should be:
Or if you need list of list at the output then:
一种丑陋的方法是使用 evalf:
如果您不介意一个数组中的所有数字,您可以:
an ugly way is to use evalf:
if you don't mind all your numbers in one array you could go:
为了映射具有任意数量维度的列表,您可以使用 numpy.apply_over_axes
不幸的是,如果您还需要更改变量类型,则这不起作用。没有找到任何库解决方案,所以这里是执行此操作的代码:
In order to map list with any number of dimensions you could use numpy.apply_over_axes
Unfortunately that doesn't work if you also need to change variable type. Didn't find any library solution for this, so here is the code to do that: