Py学习  »  Laurent LAPORTE  »  全部回复
回复总数  3
5 年前
回复了 Laurent LAPORTE 创建的主题 » 如何根据python中的数字列表生成数量?

print("1" * 5)
# 11111

values = "132"
list1 = [2, 1, 3]
result = []
for value, count in zip(values, list1):
    result.extend(value*count)
print(result)
# -> ['1', '1', '3', '2', '2', '2']

您还可以使用 int

values = [[1], [2], [3]]
list1 = [2, 1, 3]
result = []
for value, count in zip(values, list1):
    result.extend(value*count)
print(result)
# -> [1, 1, 2, 3, 3, 3]
6 年前
回复了 Laurent LAPORTE 创建的主题 » 如何在Python中对一组字符正确使用“Replace”方法

你的用法 replace 是错误的,因为您正在搜索字符串文本%d。这不是正则表达式。

您可以这样修复代码:

import re

words = ['Duration12:14254', 'Noun', 'Adjective7:888']
result = [re.sub(r'[0-9]+', r'[\g<0>]', w) for w in words]
repResult = [re.sub(r':\[(\d+)\]', r':\1', w) for w in result]
print(repResult)

你得到:

['Duration[12]:1', 'Noun', 'Adjective[7]:8']

['Duration12:14254', 'Noun', 'Adjective7:888'] ,您将得到:

['Duration[12]:14254', 'Noun', 'Adjective[7]:888']

可以使用单个RegEx简化此代码:

import re

words = ['Duration12:14254', 'Noun', 'Adjective7:888']
result = [re.sub(r'(\d+):(\d+)', r'[\1]:\2', w) for w in words]
6 年前
回复了 Laurent LAPORTE 创建的主题 » 将所有默认值移到一个python文件中

在imo中,您可以使用经典的方法,将每个类放在一个模块中。

worker_type.py :

import enum

class WorkerType(enum.Enum):
    A = 'A'
    B = 'B'

metric_type.py 以下内容:

import enum

class MetricType(enum.Enum):
    EUCLID = 'euclid'
    MANHATTAN = 'manhattan'

然后您可以这样定义配置文件:

import worker_type
import metric_type

DEFAULT_WORKER_TYPE = worker_type.WorkerType.A
DEFAULT_METRIC_TYPE = metric_type.MetricType.EUCLID

这样,你的 worker.py 保持不变:

import config

class Worker:
    def __init__(self, worker_type=config.DEFAULT_WORKER_TYPE):
        pass