Py学习  »  ggorlen  »  全部回复
回复总数  4
5 年前
回复了 ggorlen 创建的主题 » 错误:带有regex的Python脚本中的错误转义

如果你 zip ,你只能得到成对的火柴。考虑到搜索的性质,您可以将大海捞针连接成一个空格分隔的字符串,并将针连接成一个交替的模式,然后 findall 突然离开:

>>> import re
>>> needles = ['brasil', 'argentina', 'chile', 'canada']
>>> haystack = ['brasil.sao_paulo', 'chile', 'argentina']
>>> re.findall(r"\b%s\b" % "|".join(needles), " ".join(haystack), re.I)
['brasil', 'chile', 'argentina']

背后的意图 \\ 在最初的regex中是不清楚的,所以我想你想要 \b 在图案的两边。

如果希望保持算法不变,可以使用默认参数:

def persistence(n, counter=0):
    product = 1

    for i in str(n):
        product *= int(i)

    if product < 10:
        return counter + 1

    return persistence(product, counter + 1)

print(persistence(39))

尽管如此,正如@tomkarzes指出的,没有必要 counter 参数(或递归)——将结果返回调用堆栈,而不是向上传递。除了当前的 n 决定坚持。

def persistence(n):
    product = 1

    for i in str(n):
        product *= int(i)

    if product < 10:
        return 1

    return persistence(product) + 1

print(persistence(39))
5 年前
回复了 ggorlen 创建的主题 » python切片和替换

这将根据 f . [-f:] 提取最后一个 f 作为新列表的列表元素和 [:-f] 将列表的开头提取到 len(nums) - f 作为一个新的列表。

nums[:] 使用内存临时存储删除的对象( recycle_on_stack / recycle )把新的复制到列表中。 [:] 意味着我们要穿越整个建筑 norig 是名单的全部长度,我们必须

s = norig * sizeof(PyObject *);
memcpy(recycle, &item[ilow], s);

在整个名单上。见 source code .

切片赋值发生变化 nums in place ,有点像拼接操作,但在本例中没有必要使用它,因为直接赋值将获得相同的结果:

nums = nums[-f:] + nums[:-f]

+ 在这种情况下 list concatenation . 操作将创建并返回一个新列表。但是,自从 小精灵 如果被覆盖,则其上一个值将转到垃圾收集器(如果没有其他对象引用它)。

我在数至少4整本 纽斯 在上面的例子中(这两个切片相加为一个,一个用于连接,另两个用于切片分配)。

您可以使用两个regex操作。第一个通过匹配 ^[a-zA-Z\s\(\)]*$ ,然后第二个使用正向先行收集所需子字符串: .*?(?= [A-Z]) .

import re

my_try = ['a bb Aas','aa 1 Aasdf','aa bb (cc) AA','aaa ASD','aa . ASD','aaaa 1 bb Aas']
filtered = [x for x in my_try if re.match(r'^[a-zA-Z\s\(\)]*$', x)]
result = [re.match(r'.*?(?= [A-Z])', x).group(0) for x in filtered]

print(result) # => ['a bb', 'aa bb (cc)', 'aaa']

如果预期某些字符串可能会通过筛选(即,包含除字母字符、括号或空格之外的其他内容),但可能与lookahead不匹配,则需要筛选中间结果:

import re

my_try = ['a bb Aas','aaa ASD','aa . ASD','aaaa 1 bb Aas', '']
#                                                          ^^ could cause problems
filtered = [x for x in my_try if re.match(r'^[a-zA-Z\s\(\)]*$', x)]
matches = [re.match(r'.*?(?= [A-Z])', x) for x in filtered]
result = [x.group(0) for x in matches if x]

print(result) # => ['a bb', 'aaa']