Lua/Torch中的枚举函数

3
在Python中,我们使用for i, _ in enumerate(wx):,其中wx是一个行矩阵或表格。在Lua/Torch中,我们如何使用它?有任何枚举函数吗?
1个回答

1
在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.

Otherwise, returns three values: the next function, the table t, and nil, so that the construction

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

will iterate over all key–value pairs of table t.

你也可以使用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. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

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. You may however modify existing fields. In particular, you may clear existing fields.


@Sibi 可以这样写:a= { 1, 2, 3 } - hjpotter92
在Lua中,如果您使用表格,则可以使用以下代码:a={1,2,3} for i,v in ipairs(a) do print(i,v) end - moteus
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Sibi
a不是一个表格,而是一个二维张量,因此请使用apply或使用a:totable()进行转换。另请参阅:https://dev59.com/QZHea4cB1Zd3GeqPt8l8 - deltheil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接