对于何时首选列表理解而不是循环,是否有一般规则?例如:for
单个 for 循环在转换为理解时非常有用:
l = []
for word in sentence:
l.append(word)
# [word for word in sentence]
双倍可能也是:
l = []
for word in sentence:
for letter in word:
l.append(letter)
# [letter for word in sentence for letter in word]
但是,我认为在那之后可读性会变得非常差。例如,使用 s:if
l = []
for word in sentence:
if word.startswith('u'):
for letter in word:
if letter in ('a', 'b', 'c', 'o'):
l.append(letter)
# [letter for word in sentence if word.startswith('u') for letter in word if letter in ('a', 'b', 'c', 'o')]
对于循环模式的复杂性,是否有建议,在循环模式中,尝试将其放入列表理解中会更糟?for
繁星点点滴滴
慕妹3242003
炎炎设计
相关分类