2

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) 
3
  • 1
    You have not asked a question! ;-)
    – Achim
    Apr 22, 2011 at 17:08
  • 1
    Shadowing names of built-ins is a bad idea. Choose a more descriptive name that actually says somethough about what these strings and numbers represent.
    – user395760
    Apr 22, 2011 at 17:08
  • @delnan, I that for clarity of Q.
    – Merlin
    Apr 22, 2011 at 17:30

4 Answers 4

5

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
2
  • Is str_data, float_data ordered by orginal L? Does this order change?
    – Merlin
    Apr 22, 2011 at 17:27
  • 2
    The order is preserved, so as long as each tuple in L is ordered the same way you are guaranteed that str_data will be the string and float_data will be the Decimal. Apr 22, 2011 at 17:30
3

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:
3

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
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.