简体   繁体   中英

Way to pass multiple parameters in a for loop?

My code:

seperated = startContent.split(' ')
seperatedNum = len(seperated)

#Ask for user input

for word in seperated and for i in seperatedNum:
    if word == 'ADJECTIVE':
        seperated[i] = input('Enter an adjective:')
    elif word == 'NOUN':
        seperated[i] = input('Enter a noun:')
    elif word == 'ADVERB':
        seperated[i] = input('Enter an adverb:')
    elif word == 'VERB':
        seperated[i] = input('Enter a verb:')

Basically asking the user input each time they run into one of the following words (there can be multiple of each).

I get my sentence, split it into a list with split command. And run the loop for each word. I want to then edit the list using list[x] = 'replacement' method.

The word in seperated , returns the listitem. So I need another argument passed to it, eg i in len(list) to then get the accurate index of the word. I can't use list.index(str) because it returns the first index of the string when there are multiple iterations of the text.

You're looking for a way to pass multiple parameters in a for loop: There is nothing special about a for loop in this regard. The loop will iterate over a given sequence and will, each iteration, assign the current element to the given left-hand side.

for LEFT_HAND_SIDE in SEQUENCE

Python also supports "automatic" unpacking of sequences during assigments, as you can see in the following example:

>>> a, b = (4, 2)
>>> a
4
>>> b
2

In conclusion, you can just combine multiple variables on the left-hand side in your for loop with a sequence of sequences:

>>> for a, b in [(1, 2), (3, 4)]:
...     print(a)
...     print(b)
... 
1
2
3
4

That for loop had two assignments a, b = (1, 2) and a, b = (3, 4) .

In you specific case, you want to combine the value of an element in a sequence with its index. The built-in function enumerate comes in handy here:

>>> enumerate(["x", "y"])
<enumerate object at 0x7fc72f6685a0>
>>> list(enumerate(["x", "y"]))
[(0, 'x'), (1, 'y')]

So you could write your for loop like this:

for i, word in enumerate(seperated)

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