在Python中使用bool添加功能

莎拉·弗莱彻(Sarah Fletcher)

在这里的初学者,正在寻找有关python的帮助!

现在,我定义了一个函数,该函数返回列表列表:

def lenumerate(s):
    a = (text.split())
    b = ([len(x) for x in text.split()])
    c = list(zip(a,b))
    print
    return c

text = "But then of course African swallows are nonmigratory"
l = lenumerate(text)
print(l)        

它打印出来:

[('But', 3), ('then', 4), ('of', 2), ('course', 6), ('African', 7), ('swallows', 8), ('are', 3), ('nonmigratory', 12)]

现在,我想编写该函数的第二个版本,该函数将名为flip的布尔值(即True或False)作为第二个参数。翻转的默认值应为False。

我可以颠倒顺序,以便在开始时显示“非迁移性”,但这不是我想要的。我希望保留顺序,直到完全翻到(3,“ But')。

感谢您提供的任何帮助!

pp

这是一种解决方案:

def lenumerate(s, flip=False):
    a = text.split()
    b = map(len, a)
    c = zip(a, b) if not flip else zip(b, a)
    return list(c)

text = "But then of course African swallows are nonmigratory"
l = lenumerate(text, True)
print(l)

# [(3, 'But'), (4, 'then'), (2, 'of'), (6, 'course'), (7, 'African'), (8, 'swallows'), (3, 'are'), (12, 'nonmigratory')]

说明

  • 您只需要申请split()一次。
  • 您可以map直接输入zip这意味着懒惰地完成了更多的工作,而不是建立不必要的列表。
  • Python支持单行if/else构造的惰性三元语句
  • print没有参数语句没有用,可以删除。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章