如何解决在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尚未打印出来。
解决方法
在这种情况下,基本上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))
。
让我们从切入正题开始:
my_list = ["abc-123","345-abc","345","and-123"]
all_ABCs = [s for s in my_list if "abc" in s]
x = len(all_ABCs)
print(f"There are {x} items with 'abc' in the list")
for _ in range(x):
first_item = all_ABCs.pop(0)
print(first_item)
输出:
There are 5 items with 'abc' in the list
abc-123
345-abc
abc-456
abc-789
abc-101112
现在要注意一些事项:
-
您看不到最后一项,因为您要在打印之前将其删除。使用
pop
代替del
。 -
您正在遍历循环中正在更改的列表。遍历列表的 length ,而不是列表本身。
-
您正在调用列表
list
,这是Python中的保留字,对于列表来说,这通常是不好的做法,我建议改用list_
,请读{{3 }},以获取有关Python下划线的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。