简体   繁体   中英

Python 3: for loop syntax with dictionary

The following code snippet works:

param = {}

for nround_counter in [1,2,3]:
    { 
        print(nround_counter)
        #param = {'objective' : 'multi:softmax'}

    } 

But the following doesn't:

param = {}

for nround_counter in [1,2,3]:
    { 
        print(nround_counter)
        param = {'objective' : 'multi:softmax'}

    } 

The error given is invalid syntax. I am new to Python, and seek help in debugging the above.

Thank you.

Bodies of code such as loops, functions, classes, etc. are not enclosed by braces in Python. Indentation is what determines code structure.

for nround_counter in [1, 2, 3]:
    print(nround_counter)
    param = {'object' : 'multi:softmax'}

You're conflating much different issues here.

Here's your first example, rendered with whitespace more conventionally used for Python:

#!python3
param = {}

for nround_counter in [1,2,3]:
    { print(nround_counter) }

Note that this is iterating over a series of statements, the statement is (uselessly and confusingly) being coded into a set literal constructor expression, being called for its side effect (calling the print function). It's not modifying any state, but it's evaluated as a set, containing the None singleton as its only element, on each iteration through the loop.

This is not a special syntax. It's just an incomprehensible usage of Python's set literal construction syntax.

It's also completely unclear what you're trying to accomplish. It make no sense to loop over a list continually binding param to the same literal dictionary contents over and over.

Perhaps if you wanted to build some sort of table?

param = dict()
for n in range(1,4):
    print(n)
    param['objective%s'%n] = 'multi:softmax'

... or something like that. Note I initialize param with dict() rather than the literal {} because I think it's a bit cleaner and more clear, if slightly more verbose. Also I'm using range(1,4) rather than your literal list, again because it's cleaner. What I'm doing in the body of this loop is silly, but it's an example of what you could do.

Note that I'm generating a unique key (a constant string literal with interpolation of the string representation of my iterator variable) for each pass through the loop. One would normally expect the values to also be dynamically computed or derived in some way; but I don't how that as there's no clear pedagogical example that comes to mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM