社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  mozway  »  全部回复
回复总数  32
3 年前
回复了 mozway 创建的主题 » Python中数组的智能取整

一种自动化的方法可以是计算所有的绝对差异,得到最小值,并找出保留代表性差异的小数位数。

这不会给出您想要的确切输出,但遵循一般逻辑。

这里使用numpy来帮助计算,算法是 O(n**2) :

def auto_round(l, round_int_part=False):
    import numpy as np
    a = np.array(l)
    b = abs(a-a[:,None])
    np.fill_diagonal(b, float('inf'))
    n = int(np.ceil(-np.log10(b.min())))
    # print(f'rounding to {n} decimals') # uncomment to get info
    if n<0:
        if not round_int_part:
            return a.astype(int).tolist()
        return np.round(a, decimals=n).astype(int).tolist()
    return np.round(a, decimals=n).tolist()

auto_round([17836.987, 17836.976, 17836.953])
# [17836.99, 17836.98, 17836.95]

auto_round([0.6726, 0.6785, 0.6723])
# [0.6726, 0.6785, 0.6723]

auto_round([17836.982, 160293.673, 103974.287])
# [ 17836, 160293, 103974]

auto_round([17836.982, 160293.673, 103974.287], round_int_part=True)
# [20000, 160000, 100000]
3 年前
回复了 mozway 创建的主题 » 如何在python中使用for循环替换字符串中的字符?

你试图修改整个字符串,而你应该只处理字符。

修改代码时,这将是:

a = '(L!ve l@ugh l%ve)'
spe = set("+=/_(*&^%$#@!-.?)") # using a set for efficiency

for char in a:
    if char in spe:
        print('*', end='')
    else:
        print(char, end='')

输出: *L*ve l*ugh l*ve*

更具蟒蛇风格的方式是:

spe = set("+=/_(*&^%$#@!-.?)")
print(''.join(['*' if c in spe else c  for c in a]))