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