在python中使用bool添加函数

2024-09-30 02:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

初学者在这里,寻找一些帮助与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”)

我很感激你能提供的任何帮助


Tags: of函数textfalse列表arebutsplit
3条回答

Python functions can be called with a single list of arguments,而不是多个单独的参数

根据flip的状态,我们可以使用它来生成一组参数和一组相反的参数

def lenumerate(s, flip=False):
    words = text.split()
    word_lengths = [len(x) for x in text.split()]
    args = [words, word_lengths] if flip else [word_lengths, words]
    return list(zip(*args))


text = "But then of course African swallows are nonmigratory"

print(lenumerate(text))
print(lenumerate(text, True))

印刷品

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

注意事项

  • 你刚才用的括号是多余的
  • 尽量使用会说话的变量名,而不是ab

Python的列表理解使得首先避免编写函数成为可能。上述函数可以写成:

result = [(word, len(word)) for word in text.split()]
print(result)

这里有一个解决方案:

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语句没有用处,可以删除
def lenumerate(s, flip=False): ## Default value is False if not provided
    a = (text.split())
    b = ([len(x) for x in text.split()])
    c = list(zip(a,b))

    if list: ## Reverse the pairs if you want to
        c = list(zip(b, a))

    return c

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

相关问题 更多 >

    热门问题