这是我的代码;
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))
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句