Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 制作包含(i,i*i)的字典,其中i是从1到n_Python 3.x_Dictionary_For Loop_Numbers_Range - Fatal编程技术网

Python 3.x 制作包含(i,i*i)的字典,其中i是从1到n

Python 3.x 制作包含(i,i*i)的字典,其中i是从1到n,python-3.x,dictionary,for-loop,numbers,range,Python 3.x,Dictionary,For Loop,Numbers,Range,输入格式: 把数字n放在一行中 输出格式: 将词典d打印成一行 期望的行为,对于输入8,字典: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 我尝试的是: n=int(input()) for i in range(1,n+1): a=i*i print("{",i,": ",a,"}",sep="") 对于输入6,它给了我什么: {1: 1} {2: 4} {3: 9} {4: 16} {5: 25} {6: 3

输入格式:

把数字n放在一行中

输出格式:

将词典d打印成一行

期望的行为,对于输入8,字典:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
我尝试的是:

n=int(input())
for i in range(1,n+1):
    a=i*i
    print("{",i,": ",a,"}",sep="")
对于输入6,它给了我什么:

{1: 1}
{2: 4}
{3: 9}
{4: 16}
{5: 25}
{6: 36}

如果你想打印这本词典,为什么不制作一本简单的词典,而不是把它复杂化呢

n=int(input())
d = {}
for i in range(1,n+1):
    a=i*i
    d[i] = a
print(d)
您将获得预期的O/p:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

您可以在一条语句中创建dict:

d = dict((i,i*i) for i in range(1,n+1))
当n=8时,得到

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

您可以使用以下工具创建词典:

对于
10
您可以

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
单线解 解释 在
str
模块中有一个名为
join
的内置函数。有了它,您可以用指定的分隔符连接字符串列表

下面的例子

','.join(['Hello', 'World'])
将返回concat字符串

'Hello, world'
您可以看到,
join
可以很好地处理边距

但是请注意,
join
只接受一个参数,字符串列表。不能向其提供整数列表;否则,
join
将引发一个错误,提示:

TypeError: sequence item 0: expected str instance, int found
因此,您应该强制将
range
生成的整数转换为
str
字符串

参考文献

您不是在创建字典,而是在打印字符串。如果要在同一行中打印所有这些条目,则必须使用字符串连接。
'Hello, world'
TypeError: sequence item 0: expected str instance, int found