简体   繁体   English

枚举lua / torch中的函数

[英]Enumerate function in lua/torch

In python, we use for i, _ in enumerate(wx): where wx is a row matrix or table. 在python中,我们for i, _ in enumerate(wx):使用for i, _ in enumerate(wx):其中wx是行矩阵或表。 How can we use this in lua/torch. 我们如何在lua / torch中使用它。 Any enumerate function? 任何枚举函数?

In Lua, you have pairs and ipairs : 在Lua,你有pairsipairs

 pairs (t) 

If t has a metamethod __pairs , calls it with t as argument and returns the first three results from the call. 如果t有一个metamethod __pairs ,则以t为参数调用它,并返回调用的前三个结果。

Otherwise, returns three values: the next function, the table t , and nil , so that the construction 否则,返回三个值: next函数,表tnil ,以便构造

 for k,v in pairs(t) do body end 

will iterate over all key–value pairs of table t . 将迭代表t所有键值对。

You can also use next , for creating your own custom enumeration: 您也可以使用next来创建自己的自定义枚举:

 next (table [, index]) 

Allows a program to traverse all fields of a table. 允许程序遍历表的所有字段。 Its first argument is a table and its second argument is an index in this table. 它的第一个参数是一个表,它的第二个参数是该表中的索引。 next returns the next index of the table and its associated value. next返回表的下一个索引及其关联值。 When called with nil as its second argument, next returns an initial index and its associated value. 当使用nil作为其第二个参数调用时, next返回初始索引及其关联值。 When called with the last index, or with nil in an empty table, next returns nil . 当使用最后一个索引调用时,或者在空表中使用nil时, next返回nil If the second argument is absent, then it is interpreted as nil. 如果第二个参数不存在,则将其解释为nil。 In particular, you can use next(t) to check whether a table is empty. 特别是,您可以使用next(t)来检查表是否为空。

The order in which the indices are enumerated is not specified, even for numeric indices . 未指定索引的枚举顺序, 即使对于数字索引也是如此 (To traverse a table in numerical order, use a numerical for .) (要遍历表中数字顺序, 使用的数值。)

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. 如果在遍历期间将任何值分配给表中不存在的字段,则next的行为是未定义的。 You may however modify existing fields. 但是,您可以修改现有字段。 In particular, you may clear existing fields. 特别是,您可以清除现有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM