在我的代码中,我有以下内容:
if all(requiredField in submittedFields for requiredField in requiredFields):
# all required fields in submittedFields exist
else:
# error handling
目标是检查requiredFields
中的字符串列表是否都存在于submittedFields
中
{>当一个字符串的长度小于1}时有效。但是,当你有
^{pr2}$然后for循环迭代每个字符,而不是字符串本身。在
所以我的问题是,除了
try:
requiredFields.sort()
# requiredFields is a list of strings
except AttributeError:
# requiredFields is a string list whose length == 1
使用python集将更加高效:
有几个优化可以加快速度:
注意。看起来你最初的问题是元组表示法。史蒂文·鲁姆巴尔斯基很好地阐述了这一点。当然,如果使用集合,这就不成问题了。在
祝您的字段验证好运:-)
元组不是用括号括起来的字符串。要创建一个单项元组,您需要一个尾随逗号:
有关更多信息,请参阅Tuple Syntax堆栈溢出问题Python tuple comma syntax rule上的wiki。在
首先,你不应该有
requiredFields = ('single element')
——如果你想要一个元组,你应该写requiredFields = ('single element',)
。在但假设您无法控制您的输入,最常见的测试方法是:
相关问题 更多 >
编程相关推荐