小编Jam*_*ith的帖子

从字符串中提取单词,删除标点符号并返回带有分隔单词的列表

我想知道如何实现一个函数get_words(),返回列表中的字符串中的单词,剥离标点符号.

我多么想拥有它实行的是取代不可string.ascii_letters'',并返回.split().

def get_words(text):

    '''The function should take one argument which is a string'''

    returns text.split()
Run Code Online (Sandbox Code Playgroud)

例如:

>>>get_words('Hello world, my name is...James!')
Run Code Online (Sandbox Code Playgroud)

收益:

>>>['Hello', 'world', 'my', 'name', 'is', 'James']
Run Code Online (Sandbox Code Playgroud)

python string list

17
推荐指数
3
解决办法
5万
查看次数

如何重复一次功能n次

我正在尝试在python中编写一个函数,如:

def repeated(f, n):
    ...
Run Code Online (Sandbox Code Playgroud)

where f是一个带有一个参数的函数,n是一个正整数.

例如,如果我将square定义为:

def square(x):
    return x * x
Run Code Online (Sandbox Code Playgroud)

我打来电话

repeated(square, 2)(3)
Run Code Online (Sandbox Code Playgroud)

这将是3次,2次.

python higher-order-functions

5
推荐指数
3
解决办法
4万
查看次数

如何在没有调用abs的情况下将b添加到b的绝对值

我在定义一个函数时遇到了一些问题.我试图在没有调用abs的情况下将b添加到b的绝对值

from operator import add, sub
def a_plus_absolute_b(a, b):
    """Return a+abs(b), but without calling abs."""
    if b < 0:
        op = add(a, (b * -1))
    else:
        op = add(a, b)
    return op(a, b)
Run Code Online (Sandbox Code Playgroud)

python function

0
推荐指数
2
解决办法
2519
查看次数

标签 统计

python ×3

function ×1

higher-order-functions ×1

list ×1

string ×1