2013-01-13 252 views
0

对于某些人来说这可能是微不足道的,但我无法在Python中查看2d数组(?)。Python循环遍历列表

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

如何循环浏览此列表?我试过这个,但显然这不起作用。

for item in orderList: 
     print item; 

**如果你可以指导我的教程或网站有这个信息,我会满足。

+1

你期望输出什么?你有什么作品... – Tim

+0

你有没有尝试删除分号? – Ernir

+0

@Ernir:分号是多余的,不是非法的 – inspectorG4dget

回答

10

您可以使用元组通过一切拆包循环:

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' 
+0

谢谢!!正是我需要的 – ealeon

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) 
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'。地图也可以返回一个值。如果你想将每种水果的价格或数量提高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(fruit) for fruit in orderList ] 
[ display(fruit) for fruit in generate ]