2011-04-22 42 views
1

两个元素在Python列表我每个元件具有两个项目,1日海峡,第二浮子在使用Python中

L= [('A', Decimal('52.00')), ('B', Decimal('87.80')), ('G', Decimal('32.50'))] 

我想用一个for loop中的元素既项循环

NewL= [] 
for row in L: 

    ### do something with str 
    InSql= "SELECT " % str 
    f= csr.execute(InSql) 
    ns = list(f) 

    ###do something with float 
    InSql= "SELECT " % float 
    f= csr.execute(InSql) 
    nf = list(f) 

    NewL.append(str, float,ns, nf) 
+1

你还没有问了一个问题! ;-) – Achim 2011-04-22 17:08:08

+1

隐藏内置的名字是一个坏主意。选择一个更具描述性的名字,实际上说这些字符串和数字代表了什么。 – delnan 2011-04-22 17:08:44

+0

@delnan,我为了清晰度Q. – Merlin 2011-04-22 17:30:10

回答

4

for循环更改为这样的事情:

for str_data, float_data in L: 
    # str_data is the string, float_data is the Decimal object 
+0

+1元组拆包是一个更好的解决方案:) – 2011-04-22 17:08:47

+0

是str_data,float_data按原始L排序?这个顺序是否改变? – Merlin 2011-04-22 17:27:58

+2

订单被保留下来,只要'L'中的每个元组的排列方式与您保证'str_data'将是字符串并且'float_data'将是'Decimal'一样。 – 2011-04-22 17:30:54

2

两种方式:

首先,你可以访问成员行:

#For string: 
row[0] 
#For the number: 
row[1] 

或者你指定你的循环是这样的:

for (my_string, my_number) in l: 
2

读你的问题,我想你想要的是这样的:

L= [('A', Decimal('52.00')), ('B', Decimal('87.80')), ('G', Decimal('32.50'))] 

for my_str, my_float in L: 
    print "this is my string:", my_str 
    print "this is my fload:", my_float 
2

元组解包与循环变量一起工作:

L= [('A', Decimal('52.00')), ('B', Decimal('87.80')), ('G', Decimal('32.50'))] 
for s, n in L: 
    print "string %s" % s 
    print "number %s" % n 

。OUPUTS:

string A 
number 52.00 
string B 
number 87.80 
string G 
number 32.50