def sem1Sort1(semester1, selectionSEM1):
list = []
for period in semester1:
if period == 1:
for index in semester1[period]:
if index in selectionSEM1:
list.append(index)
return list
def sem1Sort2(semester1, selectionSEM1):
list = []
for period in semester1:
if semester1 == 2:
for index in semester1[period]:
if index in selectionSEM1:
list.append(index)
return list
def main():
selectionSEM1 = ["a", "b", "c", "d", "e", "f", "g", "h"]
selectionSEM2 = []
semester1 = {
1: ["e", "f", "g", "h"], 2: ["a", "b", "c", "d"] ,
}
SEM1period1 = sem1Sort1(semester1, selectionSEM1)
SEM1period2 = sem1Sort2(semester1, selectionSEM1)
print SEM1period1
print SEM1period2
main()
当我运行这段代码时,它会输出SEM1period1 fine,如[“e”,“f”,“g”,“h”],但是第二个方法sem1Sort2似乎不会将任何内容保存到SEM1period2中-因为print语句会输出[]
更新:
def sem1Sort1(semester1, selectionSEM1):
list = []
for period in semester1:
if period == 1:
for index in semester1[period]:
if index in selectionSEM1:
list.append(index)
return list
def sem1Sort2(semester1, selectionSEM1):
list = []
for period in semester1:
if period == 2:
for index in semester1[period]:
if index in selectionSEM1:
list.append(index)
return list
def sem1Sort3(semester1, selectionSEM1):
list = []
for period in semester1:
if period == 3:
for index in semester1[period]:
if index in selectionSEM1:
list.append(index)
def main():
selectionSEM1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
selectionSEM2 = []
semester1 = {
1: ["e", "f", "g", "h"], 2: ["a", "b", "c", "d"] ,
3: ["i", "j", "k", "l"]
}
SEM1period1 = sem1Sort1(semester1, selectionSEM1)
SEM1period2 = sem1Sort2(semester1, selectionSEM1)
SEM1period3 = sem1Sort3(semester1, selectionSEM1)
print SEM1period1
print SEM1period2
print SEM1period3
main()
为什么print SEM1period3不返回none?你知道吗
为什么这么复杂?你知道吗
你不需要循环所有的dict条目并找出匹配的条目-这使得dict的整个用法毫无意义。你知道吗
相反,您可以告诉dict为您提供与给定键相关联的值。您可以在
main()
函数中这样做,将函数简化为可以在
main()
函数中调用你会得到你想要的。你知道吗
您甚至可以对其进行优化:
集合使查找更快。你知道吗
更紧凑。你知道吗
这里比较
semester1
和integer,但是semester1
是sem1Sort2
函数中的dict
对象实际上,您必须将整数与
dict
的键进行比较,如下所示你剩下的时间都是这样
输出:
相关问题 更多 >
编程相关推荐