Python for循环遍历lis

2024-04-29 00:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我输入"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)

Tags: appleforiscreate条件chunkspiestr
3条回答

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

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

我改为使用Python自己的str.isupper()测试来测试tidbit的第一个字符:

^{pr2}$

下一个理解是,使用一个有条件的列表来创建一个有条件的列表,因为它有两个很可怕的副作用:

list1 = [tidbit for tidbit in chunks if tidbit[0].isupper()]
list2 = [tidbit for tidbit in chunks if not tidbit[0].isupper()]
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]

您可以在此处使用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'])

帮助(上部结构)

^{pr2}$

相关问题 更多 >