![](/img/trans.png)
[英]Find and print the indexes of a substring in string that starts and ends with a specific character in python
[英]How to find indexes of string in lists which starts with some substring?
我有一些像這樣的列表:
lines = [
"line",
"subline2",
"subline4",
"line",
]
我想獲取以某些子字符串開頭的行索引列表。
我用這種方法:
starts = [n for n, l in enumerate(lines) if l.startswith('sub')]
但也許有人知道更美麗的方法嗎?
我知道已經有一段時間了,因為這個問題很活躍,但是如果有人感興趣的話,這是另一個解決方案。
你的方式似乎很好,但這是一個類似的策略,使用list.index()
方法:
starts = [lines.index(l) for l in lines if l.startswith('sub')]
至於時間的推移,這兩個功能的時鍾在大約相同的(平均1.7145156860351563e-06
秒鍾的enumerate
的解決方案和1.7133951187133788e-06
秒鍾,我.index()
解決方案)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.