Merlin
Merlin

Reputation: 25639

In For loop using two elements in python

In python list I have two items per element, 1st a str, second a float

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

I want use a for loop both item in the element

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) 

Upvotes: 2

Views: 857

Answers (4)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

Tuple unpacking works with loop variables:

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

Upvotes: 3

Matty P
Matty P

Reputation: 100

Reading your question, I think what you want is this:

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

Upvotes: 3

tillsten
tillsten

Reputation: 14878

Two ways:

First you could access the members of row:

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

Or you specify your loop this way:

for (my_string, my_number) in l:

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208475

Change your for loop to something like this:

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

Upvotes: 5

Related Questions