Python – 在列表中查找包含字符串的索引
给定一个列表,任务是编写一个Python程序来查找包含字符串的索引。
例子:
Input: [‘sravan’, 98, ‘harsha’, ‘jyothika’, ‘deepika’, 78, 90, ‘ramya’]
Output: 0 2 3 4 7
Explanation: Index 0 2 3 4 7 contains only string.
方法一:在for循环中使用type()运算符
通过使用 type()运算符,我们可以从列表中获取字符串元素的索引,字符串元素将属于 str() 类型,因此我们使用 for 循环遍历整个列表并返回字符串类型的索引。
Python3
# create a list of names and marks
list1 = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# display
list1
# iterate through list of elements
for i in list1:
# check for type is str
if(type(i) is str):
# display index
print(list1.index(i))
Python3
# create a list of names and marks
list1 = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# display
list1
# list comprehension
print([list1.index(i) for i in list1 if(type(i) is str)])
# list comprehension display strings
print([i for i in list1 if(type(i) is str)])
输出:
0
2
3
4
7
方法二:在列表理解中使用 type()运算符
通过使用列表推导,我们可以获得字符串元素的索引。
Syntax: [list.index(iterator) for iterator in list if(type(iterator) is str)]
Python3
# create a list of names and marks
list1 = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# display
list1
# list comprehension
print([list1.index(i) for i in list1 if(type(i) is str)])
# list comprehension display strings
print([i for i in list1 if(type(i) is str)])
输出:
[0, 2, 3, 4, 7]
['sravan', 'harsha', 'jyothika', 'deepika', 'ramya']