更多pythonic方式来处理这种逻辑结构

时间:2014-06-12 17:54:38

标签: python loops refactoring

我需要将一长串的数字分成100块以及剩余的数字,然后将它们添加到最后的字典中。

我能够用循环做到这一点,但我觉得我可能会遗漏一些会使这个操作变得更加清洁和高效的东西。

l = 238 # length of list to process
i = 0 #setting up count for while loop 
screenNames = {}#output dictionary
count = 0 #count of total numbers processed

while i < l:
    toGet = {}
    if l - count > 100:#blocks off in chunks of 100
        for m in range (0,100):
            toGet[count] = m
            count = count + 1
    else:
        k = count
        for k in range (0,(l - count)):#takes the remainder of the numbers 
            toGet[count] = k
            count = count + 1
        i = l   # kills loop  
    screenNames.update(toGet)
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the 
#index value

print 'returning:'
print screenNames

上面的代码有效,但是如果有人有更好的方法处理这个问题会感到笨拙吗?

2 个答案:

答案 0 :(得分:2)

据我所见,您将一个键n映射到值n % 100,因此可能会写为

screenNames = dict((i, i%100) for i in range(238))
print screenNames

答案 1 :(得分:1)

运行代码,看起来你只是在进行模运算:

l = 238 
sn = {}
for i in xrange(l):
    sn[i] = i % 100
print sn

或者更简洁:

l = 238 
print dict((i, i % 100) for i in xrange(l))

这可以通过构建基于密钥对元组的字典来实现。