[英]Python 2.7: How would I go about creating a dictionary that maps the first n numbers to their respective squares or cubes?
I currently have this piece of code (for squares), but it doesn't seem to be working correctly: 我目前有这段代码(用于正方形),但似乎无法正常工作:
for n in range(len(dict)):
if n == 0:
pass
else:
squares = (n*n)
dict[n]=squares
The parameter of range()
should be n
, because the dictionary is probably empty when you begin. range()
的参数应为n
,因为开始时字典可能为空。 Also, dict
is a builtin type in python and you shouldn't name your variables this way. 另外, dict
是python中的内置类型,您不应以这种方式命名变量。
squares = {i:i*i for i in xrange(n)}
dict={}
for i in range(n):
dict[i]=i*i
squares={}
for r in range(int(n) + 1):
if r == 0:
pass;
else:
squares[r] = (r * r)
This code will create a dictionary, look through all of the values up to n, and add the square tot he dictionary at index "r"! 这段代码将创建一个字典,浏览直到n的所有值,并在索引“ r”处添加字典的平方! This code fulfills all of the requirements you asked for! 该代码满足您所要求的所有要求! Let me know if you have any questions! 如果您有任何疑问,请告诉我!
It's not clear from the question whether dict
already contains values. 从这个问题尚不清楚dict
是否已经包含值。 Also I'm not sure why you're skipping n==0
. 另外,我不确定您为什么要跳过n==0
。
Assuming you have a list dict
with a certain length, your code should work for all values except the first (which you're skipping), except that your last line is not indented, so it's not run inside the loop. 假设您有一个具有一定长度的列表dict
,那么代码应该适用于除第一个(您正在跳过的)之外的所有值,除了您的最后一行没有缩进之外,因此它不在循环内运行。 This should do it: 应该这样做:
for n in range(len(dict)):
dict[n]=n*n
Anyway I recommend a list comprehension to do this: 无论如何,我建议您使用列表理解来做到这一点:
dict = [n*n for n in len(dict)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.