gpt4 book ai didi

python - 如何为这些 if 语句创建循环?

转载 作者:行者123 更新时间:2023-11-28 22:30:51 25 4
gpt4 key购买 nike

这是我在没有循环的情况下实现的,这是丑陋的。我确信这可以通过循环完成而无需重复语句:

def my_function(my_list_of_words):
_digits = re.compile('\d')
to_return = []

for i, p in enumerate(my_list_of_words):
new_list= []
if 'start' in p:
if bool(_digits.search(my_list_of_words[i+1])):
new_list.append(p)
new_list.append(my_list_of_words[i+1])
if bool(_digits.search(my_list_of_words[i+2])):
new_list.append(my_list_of_words[i+2])
if bool(_digits.search(my_list_of_words[i+3])):
new_list.append(my_list_of_words[i+3])
to_return.append(" ".join(new_list))

return to_return

这很好用,但我不知道在 "start" 之后会有多少个带数字的字符串。

我想要一个循环,它将继续在字符串列表中查找数字,直到下一个索引没有数字。

我试过这个:

def my_function(my_list_of_words):
_digits = re.compile('\d')
to_return = []

for i, p in enumerate(my_list_of_words):
new_list= []
count = 1
if 'start' in p:
new_list.append(p)
while bool(_digits.search(my_list_of_words[i+count])):
new_list.append(my_list_of_words[i+count])
++count
to_return.append(" ".join(new_list))

return to_return

由于某种原因这不起作用,它似乎永远循环。我也试过:

while True:
if bool(_digits.search(my_list_of_words[i+count])):
//doo things
++count
else:
break

这对我也不起作用,它会永远循环。

表示我要实现的目标:

['foo','foo','foo','start', '23', 'a32bc', '43', '332', 'foo', 'start', '23', 'a32bc']

会产生

['start 23 a32bc 43 332', 'start 23 a32bc']

假设我们有上面的列表,当我们到达 'start' 时,我想检查下一个是否有数字,在我们的例子中是 23,如果是的话, 然后检查下一个数字(包含 32 再次如此),继续这样做直到下一个没有数字。

我如何通过循环实现这一点?

最佳答案

while True: count++ 循环的 Pythonic 版本是 iterator , 结合 next() function前进到下一个元素。当迭代器耗尽时,一个 StopIteration exception被提出。

为您的列表创建一个迭代器(使用 iter() function ,然后使用嵌套循环在匹配时推进迭代器:

def my_function(my_list_of_words, _digits=re.compile('\d').search):
word_iter = iter(my_list_of_words)
digit_words = None
results = []
try:
curr = next(word_iter)
while True:
# scan to the next 'start' value
while 'start' not in curr:
curr = next(word_iter)

# collect digits; curr == start so we advance to the next
digit_words = [curr]
while True:
curr = next(word_iter)
if not _digits(curr):
break
digit_words.append(curr)
results.append(' '.join(digit_words))
digit_words = []

except StopIteration:
# out of words, append remaining digit_words if there are any.
if digit_words:
results.append(' '.join(digit_words))

return results

所以这将跳过元素,直到找到 'start',然后收集具有数字的条目,然后切换回查找 'start',等等,直到 StopIterationnext() 调用引发。

演示:

>>> my_function(['foo','foo','foo','start', '23', 'a32bc', '43', '332', 'foo', 'start', '23', 'a32bc'])
['start 23 a32bc 43 332', 'start 23 a32bc']

您可以将所有 results.append() 调用替换为 yield 以使其成为生成器。

请注意,我假设不会有任何重叠序列;例如'start' 永远不会出现在连续数字部分中带有数字的单词中。

关于python - 如何为这些 if 语句创建循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com