简体   繁体   English

Python 2.7:如何创建一个字典,将前n个数字映射到它们各自的正方形或立方体?

[英]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.

相关问题 字典。 创建一个字典,将前 n 个计数数字映射到它们的平方 - Dictionary. Create a dictionary that maps the first n counting numbers to their squares Python-我将如何去做? - Python - How would I go about doing this? 问:在python中创建一个程序来显示指定范围数字的正方形和立方体表格 - Q: Creating a program in python to display a table of squares and cubes for a specified range of numbers 我将如何在Python中创建另一个int()函数,以便我能理解它? - How would I go about creating another int() function in Python so I can understand it? 在python中,我将如何为文本冒险创建保存系统? - In python, how would I go about creating a save system for a text adventure? 我将如何创建一个可以从应用程序内部更改 Python 代码的应用程序? - How would I go about creating an app that can change python code from within the app? 如何在pygame中创建流畅的相机运动? - How would I go about creating smooth camera movement in pygame? 我将如何 go 比较 Python 中长度最长的列表? - How would I go about comparing lists with the highest length in Python? 我将如何循环 python 函数的特定部分? - How would i go about looping specific parts of a python function? 关于单击“允许位置”,我将如何 go? - Python - How would I go about clicking “Allow location”? - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM