2011-11-23 57 views
2

在我的代碼,我有以下幾點:的Python:標識字符串列表以1比字符串長度

if all(requiredField in submittedFields for requiredField in requiredFields): 
    # all required fields in submittedFields exist 
else: 
    # error handling 

的目的是檢查是否字符串在requiredFields列表全部存在於submittedFields

能正常工作時requiredFields是長度> 1。但是,當你有一個字符串列表類似

requiredFields = ('single element') 

然後超過每個C循環迭代而不是字符串本身。

所以我的問題是,是否有處理這個以外

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

回答

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 

幾個優化使這個快:

  • 套哈希表的實現,確保做一個字符之前比賽的可能性很高性格平等測試。
  • 如果兩個字符串相同(內存中的同一對象),身份檢查將繞過逐字符相等性檢查。

注意。它看起來像你原來的問題是元組符號。史蒂文倫巴爾斯基很好地解決了這個問題。當然,如果你使用集合,這將成爲一個非問題。

與現場驗證:-)

+0

-1關心提供一個例子?我知道它速度更快,但是你沒有真正回答他的問題,或者提供了一個替代方案。 –

+0

是的,它會更快的量級。 – 2011-11-23 19:52:47

+0

@SpencerRathbun雖然不是很明顯,但它確實回答了這個問題。具體而言,「是否有更多的pythonic手段來處理這一點」。問題是人們會說什麼[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –

5

括號內的字符串更Python的手段是不是一個元組 - 這是一個字符串。爲了讓你需要一個結尾逗號一個元素的元組:

>>> ('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維基。

0

好運這是因爲定義

requiredFields = ('single element') 

實際上相當於

requiredFields = 'single element' 

爲了使一個單一的元素列表,請

requiredFields = ['single element'] 

爲了使單個元素的元組,做

requiredFields = ('single element',) 
+0

如果您打算在代碼中放入一行代碼,請將其縮進四個空格或使用「{}」按鈕,而不是使用反引號。 – agf

0

首先你不應該有requiredFields = ('single element') - 如果你想有一個元組,你應該寫requiredFields = ('single element',)

但假設你沒有控制您的輸入,以測試最Python的方式是:

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

你爲什麼不只是做這樣的事情:

required = ['name', 'password'] 
submitted = ['name', 'email'] 

for field in required: 
    if field not in submitted: 
     print field + ' is required'