首页 > 解决方案 > 我可以在断言消息中引入变量的输出吗

问题描述

我正在对我创建的一个程序的输入数据进行一些验证。我正在使用断言来执行此操作。如果出现断言,我想知道数据的哪一部分出现,所以我想获得出现断言的值。

assert all(isinstance(e, int)
           for l1 in sequence.values()
           for l2 in l1 for e in l2),"Values of the dictionnary aren't lists of integers. Assert found in  '{l2}'"
# This code doesn't work

标签: python

解决方案


使用时不会,all因为它不会公开“迭代变量”。您将需要一个显式的嵌套循环。您还忘记了f''表示 f 字符串的前缀:

for l1 in [['a']]:
    for l2 in l1:
        for e in l2:
            assert isinstance(e, int), f"Values of the dictionnary 
aren't lists of integers. Assert found in  '{l2}'"
AssertionError: Values of the dictionnary aren't lists of integers. Assert found in  'a'

推荐阅读