python字符串列表中子字符串的索引

2024-05-13 03:01:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何提取python字符串列表中子字符串的索引(优先以快速方式处理长列表)?在

例如,对于mylist = ['abc', 'day', 'ghi']和字符{},我想返回[0, 1, -1]。在


Tags: 字符串列表方式字符abc中子dayghi
2条回答

您可以将^{}用于列表理解:

L = ['abc', 'day', 'ghi']

res = [i.find('a') for i in L]

# [0, 1, -1]

如文件所述:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

或带索引

l = ['abc','day','ghi']
[e.index('a') if 'a' in l else -1 for e in l]

相关问题 更多 >