我最近一直在试验Python,刚刚发现Dict理解的力量。我在Python的参考库中读到了一些关于它们的内容。下面是我在他们身上发现的例子:
>>> {x: x**2 for x in (2, 4, 6)}
{2:4, 4:16, 6:36}
对于我的迷你项目,我有以下代码:
def dictIt(inputString):
counter = 0
output = {counter: n for n in inputString}
return output
但是,我希望计数器每个循环递增1,因此我尝试使用以下有根据的猜测:
def dictIt(inputString):
counter = -1
output = {counter++: n for n in inputString}
return output
以及
def dictIt(inputString):
counter = 0
output = {counter: n for n in inputString: counter++}
return output
等等,但我的猜测都不管用。你知道吗
这是所需的I/O:
>>> print dictIt("Hello")
{0:"H", 1:"e", 2:"l", 3:"l", 4:"o"}
我怎样才能达到我的目标?你知道吗
相关问题 更多 >
编程相关推荐