简体   繁体   English

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

[英]What's the Python equivalent to iterating over a defined table in Lua?

I am very new to learning Python as I have just moved from Lua.我刚从 Lua 搬到学习 Python 方面非常陌生。 One of my questions though, is how do I iterate over a table with a given set of different values?不过,我的一个问题是,如何使用一组给定的不同值迭代表? I have tried looking on other forums, but still do not understand and would like the easiest solution possible, as well explained.我曾尝试在其他论坛上查看,但仍然不明白,并希望尽可能简单的解决方案,以及解释。

For example, I have a table of numbers, and would like to iterate through that table, printing both the key and the element of the table.例如,我有一个数字表,并且想遍历该表,打印表的键和元素。 How would I do this in Lua?我将如何在 Lua 中执行此操作?

This is what I mean when written in Lua:这就是我用 Lua 编写时的意思:

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

for i,v in pairs(table) do
    print(v)
end

I think you are trying to do this:我认为您正在尝试这样做:

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

for v in table:  # going through all elements of the list
    print(v)  # print the element

If you want to have the value and the index when going through the list, you can use enumerate like this:如果您想在遍历列表时获得值和索引,可以像这样使用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

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

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