Python中筛选符合条件的序列索引值并存储为列表的实现问题
实现方法
- 循环结束后打印循环变量
i得到6,是因为Python的for循环变量会保留最后一次迭代的赋值,range(len(testlist1))对应0到6的整数序列,循环执行完i的最终值为6。 - 用单个变量
m存储下标会被后续符合条件的值覆盖,只能保留最后一个匹配的下标5。
要得到存储所有符合条件下标的列表['1', '5'],只需要提前初始化空列表,每次匹配到符合条件的元素时,将下标转为字符串后追加到列表中即可,示例代码如下:
testlist = "I like sunny and I like cloudy" testlist1 = testlist.split() dictionary = {'like': 'love'} # 初始化空列表存储结果 result = [] for idx, word in enumerate(testlist1): if word in dictionary: result.append(str(idx)) print(result)
执行后输出为:
['1', '5']
也可以用更简洁的列表推导式实现:
result = [str(idx) for idx, word in enumerate(testlist1) if word in dictionary]
注:判断元素是否为字典的键时,不需要调用
list(dictionary.keys()),直接用元素 in 字典即可,执行效率更高。
内容的提问来源于stack exchange,提问作者HANS
相关产品推荐
相关产品推荐

