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

标签 python python-3.x

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

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']

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

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

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

相关文章:

python-3.x - Elasticsearch批量插入无法完全正常工作

python-3.x - 导入错误 : No module named 'TkTreectrl'

python-3.x - 如何使用 For-loop 和 Tell 函数填充每行的起始位置列表?

android - Android 上的 Python 3 使用 TerminalIDE

python - 是否有用于在 Django 中实现 View 模型装饰器 ala Draper 的库?

python - 从 Haskell 到函数式 Python

python - 减去python中的匹配行

如果缺少,Python 将元素添加到列表中的列表

python - 如何将 ffmpeg complex_filter 转换为 ffmpeg-python

python - 仅绘制大型 Pandas 数据框中的唯一行