2013-04-04 242 views
1

如果我輸入"apple Pie is Yummy"我想:['Pie','Yummy'] ['apple','is']的Python for循環遍歷列表

我得到:[] ['apple', 'Pie', 'is', 'Yummy']

如果我輸入"Apple Pie is Yummy"我想:['Apple','Pie','Yummy'] ['is']

我得到:['Apple', 'Pie', 'is', 'Yummy'] []

它的表現就像我的條件運算符的for循環額外的迭代不計算該條件第一次迭代過程中,只讀一次。

str = input("Please enter a sentence: ") 

chunks = str.split() 

# create tuple for use with startswith string method 
AtoZ = ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z') 

# create empty lists to hold data 
list1 = [] 
list2 = [] 

for tidbit in chunks: 
    list1.append(tidbit) if (str.startswith(AtoZ)) else list2.append(tidbit) 

print(list1) 
print(list2) 

回答

3

您正在測試錯誤的變量;你想檢查tidbit,不str

list1.append(tidbit) if (tidbit.startswith(AtoZ)) else list2.append(tidbit) 

我轉而使用Python的str.isupper()測試,而不是隻測試tidbit的第一個字符:

接下來,只需創建一個具有兩個列表列表解析,因爲使用條件表達式的副作用是非常可怕的:

list1 = [tidbit for tidbit in chunks if tidbit[0].isupper()] 
list2 = [tidbit for tidbit in chunks if not tidbit[0].isupper()] 
+0

謝謝你,我錯過了明顯。 – ptay 2013-04-04 16:53:51

0

您可以在這裏使用str.isupper()

def solve(strs): 

    dic={"cap":[],"small":[]} 

    for x in strs.split(): 
     if x[0].isupper(): 
      dic["cap"].append(x) 
     else:  
      dic["small"].append(x) 

    return dic["small"],dic["cap"] 



In [5]: solve("apple Pie is Yummy") 
Out[5]: (['apple', 'is'], ['Pie', 'Yummy']) 

In [6]: solve("Apple Pie is Yummy") 
Out[6]: (['is'], ['Apple', 'Pie', 'Yummy']) 

幫助(str.upper)

In [7]: str.isupper? 
Type:  method_descriptor 
String Form:<method 'isupper' of 'str' objects> 
Namespace: Python builtin 
Docstring: 
S.isupper() -> bool 

Return True if all cased characters in S are uppercase and there is 
at least one cased character in S, False otherwise. 
1
chunks = raw_input("Enter a sentence: ").split() 
list1 = [chunk for chunk in chunks if chunk[0].isupper()] 
list2 = [chunk for chunk in chunks if chunk not in list1] 
+0

除非'list1'很小,'list2'的創建與'[chunk for chunk in chunks if chunk [0] .isupper()]''相比具有性能劣勢。 – 2013-04-04 17:11:00