gpt4 book ai didi

python - 获取列表长度的特定百分比的索引

转载 作者:行者123 更新时间:2023-11-30 23:13:10 25 4
gpt4 key购买 nike

def get_strings(letters, max_length):
for i in range(1, max_length + 1):
for value in product(letters, repeat=i):
yield "".join(value)

comb = [i for i in get_strings(ascii_lowercase, 4)]
print "# of possible combinations: %s" % len(comb)

def perc(i, tot):
p = float(i) /float(tot)
return p * 100

marker = [x for x in range(100) if x % 10 == 0]
marker.pop(0)

# make it 10:0, 20:0, 30:0, 40:0 and so forth...
mark = dict(zip(marker, [0 for i in range(len(marker))]))
print "BEFORE:"
for i in marker:
print "%s percent index: %s" % (i, mark[i])

l = len(comb)
for i,v in enumerate(comb):
p = perc(i, l)
ip = math.ceil(p)
if ip in marker:
mark[ip] = i


print "AFTER:"
for i in marker:
print "%s percent index: %s" % (i, mark[i])

输出:

# of possible combinations: 475254
BEFORE:
10 percent index: 0
20 percent index: 0
30 percent index: 0
40 percent index: 0
50 percent index: 0
60 percent index: 0
70 percent index: 0
80 percent index: 0
90 percent index: 0
AFTER:
10 percent index: 47525
20 percent index: 95050
30 percent index: 142576
40 percent index: 190101
50 percent index: 237627
60 percent index: 285152
70 percent index: 332677
80 percent index: 380203
90 percent index: 427728

我能够使用上面的代码来做到这一点,但它看起来非常乏味并且有很多不必要的步骤(或者更确切地说可以合并或减少)。

有任何简化吗?

最佳答案

让我们逐部分解决这个问题。

首先,我们来简化一下百分比计算

perc = lambda i, t: (i * t) / 100

现在让我们简化您的标记计算

marker = xrange(10, 100, 10)

现在让我们计算列表长度的特定百分比的索引:

 for i in marker:
print '%s percent index: %s' % (i, perc(i, len(comb))

就是这样!

<小时/>

您可以将上面的内容进一步简化为简洁的三行:

 perc = lambda i, t: (i * t) / 100
for i in xrange(10, 100, 10):
print '%s percent index: %s' % (i, perc(i, len(comb))
<小时/>

如果您确实需要将标记存储在mark字典中,请使用字典理解

mark = {i: perc(i, len(comb)) for i in xrange(10, 100, 10)}
<小时/>

您的代码的整个部分可能是不必要的:

marker = [x for x in range(100) if x % 10 == 0]
marker.pop(0)

# make it 10:0, 20:0, 30:0, 40:0 and so forth...
mark = dict(zip(marker, [0 for i in range(len(marker))]))
print "BEFORE:"
for i in marker:
print "%s percent index: %s" % (i, mark[i])

l = len(comb)
for i,v in enumerate(comb):
p = perc(i, l)
ip = math.ceil(p)
if ip in marker:
mark[ip] = i

关于python - 获取列表长度的特定百分比的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29459779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com