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

Sco*_*ski 2 python python-3.x

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

if all(requiredField in submittedFields for requiredField in requiredFields):
    # all required fields in submittedFields exist
else:
    # error handling
Run Code Online (Sandbox Code Playgroud)

我们的目标是,以检查是否在一个字符串列表requiredFields全部存在于submittedFields

requiredFields长度> 1的字符串列表时,这可以正常工作.但是,当你有类似的东西时

requiredFields = ('single element')
Run Code Online (Sandbox Code Playgroud)

然后for循环迭代每个字符而不是字符串本身.

所以我的问题是,是否有更多的pythonic方法来处理这个问题

try: 
    requiredFields.sort()
    # requiredFields is a list of strings
except AttributeError:
    # requiredFields is a string list whose length == 1
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 6

使用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
Run Code Online (Sandbox Code Playgroud)

几个优化使这个快速:

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

注意.看起来你的原始问题是元组符号.Steven Rumbalski非常好地解决了这个问题.当然,如果你使用套装,这就成了一个问题.

祝你的现场验证好运:-)


Ste*_*ski 5

括在括号中的字符串不是元组 - 它是一个字符串.要创建一个项目元组,您需要一个尾随逗号:

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

有关更多信息,请参阅Tuple语法上的wiki Stack Overflow问题Python元组逗号语法规则.