Python 中相当于迭代 Lua 中定义的表的是什么?

1 python lua

我刚从 Lua 迁移过来,所以对 Python 的学习还很陌生。不过,我的问题之一是如何迭代具有给定的一组不同值的表?我尝试在其他论坛上查找,但仍然不明白,并且想要尽可能简单的解决方案,并进行了详细解释。

例如,我有一个数字表,并且想迭代该表,打印表的键和元素。我该如何在 Lua 中做到这一点?

这就是我用 Lua 写的意思:

local table = {1, 3, 5, 7;}

for i,v in pairs(table) do
    print(v)
end
Run Code Online (Sandbox Code Playgroud)

Rai*_*ida 5

我认为你正在尝试这样做:

table = [1, 3, 5, 7]  # create the list

for v in table:  # going through all elements of the list
    print(v)  # print the element
Run Code Online (Sandbox Code Playgroud)

如果你想在浏览列表时获得值和索引,你可以enumerate这样使用:

table = [1, 3, 5, 7]  # create the list

for i, v in enumerate(table):  # going through all elements of the list with their indexes
    print(i)  # print the element index
    print(v)  # print the element value
Run Code Online (Sandbox Code Playgroud)