0

This may be trivial for some but I have trouble looking through 2d array(?) in Python.

orderList = [ ('apples', 2.0), ('pears', 3.0), ('limes', 4.0) ]

How do I loop through this list? I've tried this but obviously it's not working.

for item in orderList:
        print item;

**If you can direct me to a tutorial or website that has this information, I will be content.

4

3 回答 3

11

您可以使用元组解包来遍历所有内容:

for fruit, quantity in orderList:
    print 'I have', quantity, fruit + 'es'

您也可以从for循环内部执行此操作:

for fruit_info in orderList:
    fruit, quantity = fruit_info

    print 'I have', quantity, fruit + 'es'
于 2013-01-13T01:49:44.940 回答
0

有几种方法可以遍历列表。

最常见的是每个循环

for fruit in orderList:
    print fruit

更有效的变体是使用生成器,还值得注意的是生成器是可迭代的序列。

def generator(fruits):
    for fruit in fruits:
        yield fruit

generate = generator(orderList)
firstFruit = generate.next()
// Doing complex calculations before continuing the iteration
answer = 21 + 21
secondFruit = generate.next()

更优雅的方法是使用高阶函数“map”。Map 也可以返回一个值。如果您想将每种水果的价格或数量提高 5%,您只需创建一个简单的函数。

def display(fruit):
    print fruit  // map takes in a function as an argument and applies it to each element of the sequence.

map( display, orderList )

// You could also use a generator
map( display, generate )

我能想到的最后一种方法是使用压缩。压缩是一种内置的迭代形式,现在可以在大多数标准库数据结构中使用。如果您想使用序列创建新列表,这很有用。我很懒,所以我只是重用 display 来演示语法。

[ display(fruit) for fruit in orderList ]
[ display(fruit) for fruit in generate ]
于 2013-01-13T08:56:52.467 回答
0

您的代码可以正常工作

orderList = [ ('apples', 2.0), ('pears', 3.0), ('limes', 4.0) ]
for item in orderList:
    print item;           #you don't need `;` but it is not a problem to leave it
>>>
('apples', 2.0)
('pears', 3.0)
('limes', 4.0)
于 2013-01-13T02:04:33.063 回答