Python:识别长度为1的字符串列表与字符串

2024-10-01 19:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的代码中,我有以下内容:

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

Tags: 字符串代码infieldsforifisrequired
3条回答

使用python集将更加高效:

submitted_fields = set(['length', 'width', 'color', 'single element'])
required_fields = set(['width', 'length'])
if submitted_fields >= required_fields:
    # all required fields in submittedFields exist
else:
    # error handling

有几个优化可以加快速度:

  • 集合的哈希表实现确保在进行逐字符相等性测试之前匹配的可能性很高。在
  • 如果两个字符串相同(内存中的同一个对象),则标识检查将绕过逐字符相等性检查。在

注意。看起来你最初的问题是元组表示法。史蒂文·鲁姆巴尔斯基很好地阐述了这一点。当然,如果使用集合,这就不成问题了。在

祝您的字段验证好运:-)

元组不是用括号括起来的字符串。要创建一个单项元组,您需要一个尾随逗号:

>>> ('single element') # this is not a tuple, it's a string
'single element'
>>> ('single element',) # note the trailing comma
('single element',)

有关更多信息,请参阅Tuple Syntax堆栈溢出问题Python tuple comma syntax rule上的wiki。在

首先,你不应该有requiredFields = ('single element')——如果你想要一个元组,你应该写requiredFields = ('single element',)。在

但假设您无法控制您的输入,最常见的测试方法是:

if isinstance(requiredFields, basestring):
    # requiredFields is a string
else:
    # requiredFields is iterable

相关问题 更多 >

    热门问题