Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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 如何在py中循环字典_Python_Loops_Class_Dictionary - Fatal编程技术网

Python 如何在py中循环字典

Python 如何在py中循环字典,python,loops,class,dictionary,Python,Loops,Class,Dictionary,因此,我尝试定义一个函数,在该函数中,教室的名称将作为字典生成。 但似乎有一个错误,我不能找出什么 这就是语法 def classroom(): noofclass=int(input('Enter the number of classes:')) noofdivision=int(input('Enter the number of divisions: ')) x={} for i in range(1,noofclass + 1):

因此,我尝试定义一个函数,在该函数中,教室的名称将作为字典生成。 但似乎有一个错误,我不能找出什么

这就是语法

def classroom():
    noofclass=int(input('Enter the number of classes:'))

    noofdivision=int(input('Enter the number of divisions: '))

    x={}
    for i in range(1,noofclass + 1):

        for j in range(1,noofdivision + 1):
            dict1={i:j}
            x.update(dict1)


    print(x)

classroom()
这是输出

Enter the number of classes:2
Enter the number of divisions: 2
{1: 2, 2: 2}
由于某种原因,除法或子类不接受除值以外的值 “noofdivision”。
您能否解释为什么以及如何修复此错误。

由于字典是唯一的键集合,因此每个
i
的第二次
迭代将覆盖第一次迭代

因此,对于
i=1
,键
1
用值
1
创建,然后在
j
循环的第二次迭代中,键
1
将被
2
覆盖

对于您的用例,
x
应该是
目录的
列表。尝试:

def classroom():
    noofclass=int(input('Enter the number of classes:'))
    noofdivision=int(input('Enter the number of divisions: '))
    x=[]
    for i in range(1,noofclass + 1):
        for j in range(1,noofdivision + 1):
            x.append({i:j})
    print(x)

classroom() # output: [{1:1},{1:2}, {2:1}, {2:2}]

由于字典是唯一的键集合,因此每个
i
的第二次
j
迭代将覆盖第一次迭代

因此,对于
i=1
,键
1
用值
1
创建,然后在
j
循环的第二次迭代中,键
1
将被
2
覆盖

对于您的用例,
x
应该是
目录的
列表。尝试:

def classroom():
    noofclass=int(input('Enter the number of classes:'))
    noofdivision=int(input('Enter the number of divisions: '))
    x=[]
    for i in range(1,noofclass + 1):
        for j in range(1,noofdivision + 1):
            x.append({i:j})
    print(x)

classroom() # output: [{1:1},{1:2}, {2:1}, {2:2}]

请给出输入、输出和预期输出的完整示例。字典中的键是唯一的-每个键只能存储一个值
j
。请回答您的问题,以澄清您期望的输出。还请注意,您可以直接分配
x[i]=j
,而不是构建单独的
dict1
并调用
x.update
。您为什么要避免零索引?我觉得这只会让以后的事情变得更复杂。我避免使用0索引,因为这些是类的子类。比如1.1,2.1等等。你能给出一个完整的例子,说明什么是输入,什么是输出,什么是预期输出,请?字典中的键是唯一的-对于每个键
i
,只能存储一个值
j
。请回答您的问题,以澄清您期望的输出。还请注意,您可以直接分配
x[i]=j
,而不是构建单独的
dict1
并调用
x.update
。您为什么要避免零索引?我觉得这只会让以后的事情变得更复杂。我避免使用0索引,因为它们是类的子类。比如1.1,2.1等等,是由
dict
s的
list
组成的吗?只有一个键和值的字典通常很难使用,因为不能直接访问该值。元组/命名元组的
列表
列表
dict
似乎更合适。谢谢它起作用了。我试着给x分配一个列表值,而不是一个dict。为什么
list
dict
s?只有一个键和值的字典通常很难使用,因为不能直接访问该值。元组/命名元组的
列表
列表
dict
似乎更合适。谢谢它起作用了。我尝试为x分配一个列表值,而不是dict