代码中没有错误,但是它没有被执行?

时间:2017-07-08 17:38:46

标签: python string dictionary if-statement

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)

4 个答案:

答案 0 :(得分:0)

为什么不起作用

它正在被执行。我在if语句之前添加了一个print语句,它确实打印了。

没有任何内容被打印并不意味着程序没有被执行。在你的情况下,if语句中的表达式永远不会返回true,因此不会打印任何内容。了解如何使用print()进行调试或检查。

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  print("derp")
  student = enrollment['account_key']
  if student in unique_engagement_students:
      print (enrollment)

结果:

derp
derp

<强>替代/修复:

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
  student = enrollment['account_key']
  if student in unique_engagement_students.values():
      print (enrollment)

.values()为您获取unique_engagement_students内的值。在您将studentunique_engagement_students整个字典

进行比较之前

见下面的例子:

print(unique_engagement_students)
print(unique_engagement_students.values())

结果:

{'name': 'Amruta', 'account_key': 4162}
dict_values(['Amruta', 4162])

我希望这对StackOverflow有所帮助和欢迎。如果您发现此答案或任何其他答案有帮助并解决您的问题,请将其标记为解决方案。这样它将有助于SO社区,如果其他程序员将来遇到同样的问题,他们可以更容易地找到答案。干杯!

答案 1 :(得分:0)

取代:

if student in unique_engagement_students:

通过

if student in unique_engagement_students.values():

您之前从未输入此if statement只是因为您将字典的keys与预期位于字典values中的整数进行比较。
希望这有帮助。

答案 2 :(得分:0)

你想要

enrollments=[{'name':'Kinjal','account_key':4149},
            {'name':'Amruta','account_key':4162}]

unique_engagement_students=[4162]

for enrollment in enrollments:
    student = enrollment['account_key']
    if student in unique_engagement_students:
        print (enrollment)

我会更新以添加解释。

答案 3 :(得分:0)

为什么不简单地比较account_key

enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students={'name':'Amruta','account_key':4162}

for enrollment in enrollments:
    if enrollment['account_key'] == unique_engagement_students['account_key']:
        print (enrollment)

输出:

{'name': 'Amruta', 'account_key': 4162}

现在,如果unique_engagement_students也是list的{​​{1}},那么:

dictionary

输出:

enrollments=[{'name':'Kinjal','account_key':4149},
             {'name':'Amruta','account_key':4162}]

unique_engagement_students=[{'name':'Amruta','account_key':4162}, 
                            {'name':'ABC','account_key':123}]

for enrollment in enrollments:
    if enrollment in unique_engagement_students:
        print (enrollment)