[英]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.我得到了我的句子,用 split 命令将它拆分成一个列表。 And run the loop for each word.
并为每个单词运行循环。 I want to then edit the list using
list[x] = 'replacement'
method.然后我想使用
list[x] = 'replacement'
方法编辑列表。
The word in seperated
, returns the listitem.在单词
seperated
,返回列表项。 So I need another argument passed to it, eg i in len(list)
to then get the accurate index of the word.所以我需要另一个参数传递给它,例如
i in len(list)
,然后获取单词的准确索引。 I can't use list.index(str)
because it returns the first index of the string when there are multiple iterations of the text.我不能使用
list.index(str)
因为当文本有多次迭代时它返回字符串的第一个索引。
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.您正在寻找一种在
for
循环中传递多个参数的方法:在这方面for
循环没有什么特别之处。 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: Python 还支持在赋值期间“自动”解包序列,如以下示例所示:
>>> 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
循环左侧的多个变量与一系列序列组合在一起:
>>> 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)
.该
for
循环有两个赋值a, b = (1, 2)
和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
在这里派上用场:
>>> 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
循环:
for i, word in enumerate(seperated)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.