首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取列表长度的一定百分比的索引

获取列表长度的一定百分比的索引
EN

Stack Overflow用户
提问于 2015-04-05 16:57:28
回答 2查看 668关注 0票数 1
代码语言:javascript
运行
复制
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])

产出:

代码语言:javascript
运行
复制
# 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

我能够用上面的代码做这件事,但是它看起来很乏味,而且有很多不必要的步骤(或者可以组合或减少)。

有简化吗?

EN

Stack Overflow用户

发布于 2015-04-05 17:20:22

您应该使用xrange,一些列表理解也是不必要的:

代码语言:javascript
运行
复制
from collections import OrderedDict

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

comb = [i for i in get_strings(ascii_lowercase, 4)]

print "# of possible combinations: {}".format(len(comb))

# use an OrderedDict to maintain order, create the keys using a start
# of 10 and a step size of ten
mark = OrderedDict.fromkeys(xrange(10, 100, 10),0,)

# iterate over the items to avoid unnecessary lookups
print "BEFORE:"
for k, v in mark.iteritems():
    print "{} percent index: {}".format(k, v)

l = len(comb)
# use keys of dict 
for i in mark:
    mark[i] = int(float(i) * l / 100)

print "AFTER:"
for k,v in mark.iteritems():
    print "{} percent index: {}".format(k, v)

不需要一个计算百分比的函数,除非您确实需要一个列表,否则range不应该在python2中使用。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29459779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档