首页 > 解决方案 > 在for循环Python中获取列表的第一项

问题描述

这是我的代码;

list = ["abc-123", "abc-456", "abc-789", "abc-101112"]
all_ABCs = [s for s in list if "abc" in s]
x = len(all_ABCs)
print("There are " + x + " items with 'abc' in the list")
print(all_ABCs[0])

   for x in all_ABCs:
   del all_ABCs[0]
   print(all_ABCs[0])

这是我的结果代码;

There are 4 items with 'abc' in the list
abc-123
abc-456
abc-789

我正在尝试创建一个循环,每次都打印出列表的第一项。当列表中没有更多项目时,for 循环必须停止。如您所见,这现在不起作用,最后一个 abc 没有打印出来。

标签: pythonfor-loop

解决方案


基本上for循环不是在这种情况下使用的正确循环。可以,但最好使用while循环:

spam = ["abc-123", "abc-456", "abc-789", "abc-101112", 'noabc-1234']
abcs = [item for item in spam if item.startswith('abc')]
print(f"There are {len(abcs)} items with 'abc' in the list")
print(abcs)
while abcs:
    print(abcs.pop(0))

现在,有一个问题,为什么要删除该项目只是为了打印它。这不是必需的。您可以简单地迭代列表(使用for循环)并打印项目,或者如果所有元素都是字符串,则使用print('\n'.join(abcs)).


推荐阅读