【问题标题】:How to use multiple 'if' statements nested inside an enumerator?如何使用嵌套在枚举器中的多个“if”语句?
【发布时间】:2017-01-02 19:10:33
【问题描述】:

我有一串乱七八糟的字母,有 1.2k 行长。 我正在尝试找到一个两边正好有三个大写字母的小写字母。

这是我目前所拥有的

def scramble(sentence):
    try:
        for i,v in enumerate(sentence):
            if v.islower():
                if sentence[i-4].islower() and sentence[i+4].islower():
    ....
    ....
    except IndexError:
        print() #Trying to deal with the problem of reaching the end of the list


#This section is checking if 
the fourth letters before 
and after i are lowercase to ensure the central lower case letter has
exactly three upper case letters around it

但现在我坚持下一步。我想要实现的是在(-3,4) 范围内创建一个for-loop,并检查这些字母中的每一个是否都是大写的。如果事实上小写字母的两边都有三个大写字母,那么打印出来。

例如

for j in range(-3,4):
    if j != 0:
        #Some code to check if the letters in this range are uppercase
        #if j != 0 is there because we already know it is lowercase
        #because of the previous if v.islower(): statement.

如果这没有意义,如果代码按预期工作,这将是一个示例输出

scramble("abcdEFGhIJKlmnop")

输出

EFGhIJK

一个小写字母,两边三个大写字母。

【问题讨论】:

  • 为什么不使用正则表达式?
  • 哇,人们还在玩 Python 挑战赛?很酷的豆子,很抱歉论坛已经被垃圾邮件机器人占领了。
  • 我刚找到它,所以我想我会去@MartijnPieters 是的,不幸的是,论坛不好
  • 在这种情况下不要使用循环,而是使用regex。它会更有效率。类似问题的解决方案可在:Find a lowercase letter surronded by three uppercase letters

标签: python


【解决方案1】:

这是一种“以 Python 方式”在没有
的情况下执行此操作的方法 正则表达式:

s = 'abcdEFGhIJKlmnop'

words = [s[i:i+7] for i in range(len(s) - 7) if s[i:i+3].isupper() and s[i+3].islower() and s[i+4:i+7].isupper()]
print(words)

输出是:

['EFGhIJK']

这是一种使用正则表达式的方法,
这也是 Pythonic :-)

import re
words = re.findall(r'[A-Z]{3}[a-z][A-Z]{3}', s)

【讨论】:

  • @Liam Regexen 应该是每个程序员工具包中的一个工具。您不必一直使用它们,但每隔一段时间它们就是正确的解决方案。去学习他们。
  • @LiamEmery:正则表达式(又名正则表达式)非常擅长查找某些类型的模式,因此熟悉正则表达式是一个好主意。许多编程语言都提供正则表达式工具,而正则表达式的核心语法在一种语言之间变化不大,因此一旦您了解 Python 中的正则表达式,您会发现在其他语言中使用正则表达式也很容易。
  • 您的第一个代码 sn-p 还会找到两边有超过 3 个大写字母的小写字母,但 OP 想要两边正好有 3 个大写字母。
  • 非常 Pythonic,让我的解决方案显得迟钝和臃肿 :) 总是忘记 python 中的列表操作是多么简洁
  • 对不起,我不认为“Pythonic”意味着 codegolf-ic
【解决方案2】:

如果你不能使用正则表达式

也许这个for循环可以解决问题

if v.islower():
    if sentence[i-4].islower() and sentence[i+4].islower():
         for k in range(1,4):
            if sentence[i-k].islower() or sentence[i+k].islower():
                break
            if k == 3:
               return i

【讨论】:

  • 不错。您可以在 for 循环上使用 else 子句,而不是 if k == 3:
【解决方案3】:

正则表达式可能是最简单的,使用@Israel Unterman 答案的修改版本来解释外部边缘和非上部环境,完整的正则表达式可能是:

s = 'abcdEFGhIJKlmnopABCdEFGGIddFFansTBDgRRQ'

import re
words = re.findall(r'(?:^|[^A-Z])([A-Z]{3}[a-z][A-Z]{3})(?:[^A-Z]|$)', s)

# words is ['EFGhIJK', 'TBDgRRQ']

使用(?:.) 组可防止对行首或非上层的搜索包含在匹配组中,只在结果列表中留下所需的标记。这应该考虑到 OP 列出的所有条件。

(删除了我之前的所有代码,因为它通常*糟糕*)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多