【问题标题】:List comprehension Python with multiple control flow具有多个控制流的列表理解 Python
【发布时间】:2018-04-29 09:11:58
【问题描述】:

我正在尝试转换这个函数:

templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)

进入列表理解

modified_list = ['v' for each in characters for item in vowels 
                     if item in vowels 
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`

有点卡在这里!无法弄清楚我做错了什么。

【问题讨论】:

  • 你为什么用&而不是and
  • 另外,你为什么要把所有的东西都塞进一个列表理解中?原始代码格式更具可读性。
  • 是的,请注意,如果您曾经确实阅读过您的 elif,not in vowels 将*始终是 True,因为您已经首先检查了 if each in vowels跨度>
  • @roganjosh 你想使用列表推导,因为列表推导在 python 中获得性能提升。在这种情况下,列表推导式是用于迭代返回列表的最佳结构。如果他们只是迭代一个循环而不期望从中得到一个数组,那么普通的 for 循环将是最高效的。
  • @adambullmer 我高度高度不同意。您应该在 可读 的地方使用列表理解,不使用副作用,并且您希望 list 作为最终结果。列表理解带来的性能提升是微不足道的。

标签: python list-comprehension


【解决方案1】:

有时最好在列表理解中调用一个函数。在清理内部内容的同时,仍然可以提高列表理解的速度。

def char_code(character):
  if character in vowels:
    return 'v'
  elif character in alphabet:
    return 'c'
  else:
    return '?'

print([char_code(c) for c in characters])

【讨论】:

    【解决方案2】:

    您的理解语法有几个错误。最重要的是,您将 for 子句插入到条件表达式的中间;它必须放在表达式的末尾。

    modified_list = ['v' if each in vowels else
                    ('c' if each in alphabet else '?')
                         for each in characters]
    

    我还删除了无用的 for 子句和辅音的冗余测试:当您在表达式的 else 子句中时,您已经知道它不是元音 - 无需重新测试.

    全面测试

    元音 = "aeiou" 字母=“qwertyuiopasdfghjklzxcvbnm” characters = "现在是时候了"

    templist = []
    for each in characters:
        if each in vowels:
            templist.append('v')
        elif (each in alphabet) & (each not in vowels):
            templist.append('c')
        else:
            templist.append('?')
    
    print("     original", ''.join(templist))
    
    modified_list = ['v' if each in vowels else \
                    ('c' if (each in alphabet) else '?') \
                         for each in characters]
    
    print("comprehension", ''.join(modified_list))
    

    输出:

         original ?vc?vc?ccv?cvcv
    comprehension ?vc?vc?ccv?cvcv
    

    【讨论】:

    • `\` 不需要在任何类型的括号内!
    • 对。本地编码约定,这样我们就不必记住了。
    【解决方案3】:

    只是一个换行风格提及:Is it possible to break a long line to multiple lines in Python 显示了一些选项

    在这种情况下,列表组合括号使 \ 不必要

    有时我会在行继续内使用前导空格来表示逻辑层次结构 - 在代码行继续内,前导空格在语法上被忽略

    ['v' if each in vowels
         else ('c' if each in alphabet
                   else '?')
     for each in characters]
    

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 2021-12-08
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多