【问题标题】:Python for loop iterates over listPython for 循环遍历列表
【发布时间】:2013-04-04 16:37:38
【问题描述】:

如果我输入"apple Pie is Yummy" 我想要:['Pie','Yummy'] ['apple','is']

我得到:[] ['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)

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    您正在测试错误的变量;你想检查tidbit,而不是str

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

    我会改用 Python 自己的 str.isupper() 测试,而不是只测试 tidbit 的第一个字符:

    list1.append(tidbit) if tidbit[0].isupper() else list2.append(tidbit)
    

    接下来,只需使用列表推导式创建两个列表,因为使用条件表达式的副作用非常可怕:

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

    【讨论】:

    • 谢谢,我错过了显而易见的事情。
    【解决方案2】:
    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]
    

    【讨论】:

    • 除非list1 很小,否则list2 的创建比[chunk for chunk in chunks if not chunk[0].isupper()] 有性能劣势。
    【解决方案3】:

    您可以在这里使用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.
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2018-10-26
      • 2019-04-15
      • 2017-03-05
      相关资源
      最近更新 更多