python - 在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))
.
推荐阅读
- javascript - 如何在 vuetify 的浅色主题中启用具有自定义颜色的深色模式?
- javascript - 在输入时检查输入字段值对 js 对象值
- java - 如何检查接口列表中使用了哪个实现
- python - 字符串中的第三个字符索引
- laravel - 如何在本地网络上运行“php artisan serve”
- flutter - path_provider 依赖项的 getExternalStorageDirectory() 期望什么?
- java - java.lang.NoSuchMethodError:javax.persistence.PersistenceContext.synchronization
- c++ - 并非所有值参数化测试的测试都在 GoogleTest 中运行
- encryption - 如何将 Mcrypt 迁移到 openssl 函数以使用 PHP7.3 进行加密
- rabbitmq - 是否可以在多个 AMQP 代理之间建立通信