首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python for循环遍历列表

Python for循环遍历列表
EN

Stack Overflow用户
提问于 2013-04-05 00:37:38
回答 3查看 236关注 0票数 1

如果我输入"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循环的第一次迭代期间只被读取一次,然后额外的迭代不会计算条件。

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-05 00:39:37

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

代码语言:javascript
复制
list1.append(tidbit) if (tidbit.startswith(AtoZ)) else list2.append(tidbit)

我转而使用Python自己的str.isupper()测试,只测试tidbit的第一个字符

代码语言:javascript
复制
list1.append(tidbit) if tidbit[0].isupper() else list2.append(tidbit)

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

代码语言:javascript
复制
list1 = [tidbit for tidbit in chunks if tidbit[0].isupper()]
list2 = [tidbit for tidbit in chunks if not tidbit[0].isupper()]
票数 3
EN

Stack Overflow用户

发布于 2013-04-05 00:57:16

代码语言:javascript
复制
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]
票数 1
EN

Stack Overflow用户

发布于 2013-04-05 00:43:30

您可以在此处使用str.isupper()

代码语言:javascript
复制
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'])

help(str.upper)

代码语言:javascript
复制
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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15816884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档