具有多个控制流的列表理解Python

时间:2017-11-15 23:58:53

标签: python list-comprehension

我正在尝试转换此功能:

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

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

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您的理解语法中有几处错误。最重要的是,您将# A tibble: 27 x 5 # Groups: REPORT_VALUE [16] REPORT_VALUE YEAR num total REPORT_CATEGORY <chr> <chr> <int> <int> <chr> 1 J FY14 1 25 REPORT_CODE 2 Q FY16 1 1 REPORT_CODE 3 Q FY17 1 100 REPORT_CODE 4 R FY17 1 50 REPORT_CODE 5 R FY18 2 75 REPORT_CODE 6 S FY17 2 400 REPORT_CODE 7 S FY18 2 530 REPORT_CODE 8 Check FY14 1 25 PAYMENT_METHOD 9 Check FY17 1 50 PAYMENT_METHOD 10 Check FY18 2 55 PAYMENT_METHOD # ... with 17 more rows 子句插入到条件表达式的中间;它必须在表达的最后。

for

我还删除了无用的modified_list = ['v' if each in vowels else ('c' if each in alphabet else '?') for each in characters] 子句,以及辅音的冗余测试:当你在表达式的for子句中时,你已经知道它不是元音 - 不需要重新测试。

完整测试

元音=“aeiou” alphabet =“qwertyuiopasdfghjklzxcvbnm” characters =“现在是时间”

else

输出:

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))

答案 2 :(得分:1)

只是一个突破风格的提及: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]