Python中如何用变量存储多目标字符并获取其最小索引?
如何获取输入字符串中多个目标字符的最小索引?
你原来的代码里用or和and赋值是错误的,因为Python的逻辑运算符逻辑和你想的不一样:
target_letter = "a" or "b" or "c"会直接返回第一个非空字符串(也就是"a")——非空字符串在布尔判断里属于True,or只要遇到第一个真值就会返回它,不会继续往后判断。target_letter = "a" and "b" and "c"则会返回最后一个非空字符串(也就是"c")——and会一直判断到最后一个真值才返回结果。
所以这两种写法都没法实现「匹配多个目标字符」的需求,下面是两种可行的解决方案:
方法一:收集所有目标字符的索引再取最小值
把目标字符放到一个集合(或列表)里,遍历每个字符,收集它在字符串中的索引,最后取这些索引的最小值即可。同时要处理目标字符都不在字符串里的情况,避免报错:
sentence = input("Enter input: ") target_letters = {"a", "b", "c"} # 用集合或者列表["a","b","c"]都可以 # 收集所有存在的目标字符的索引 valid_indices = [] for char in target_letters: if char in sentence: valid_indices.append(sentence.index(char)) if valid_indices: print(min(valid_indices)) else: print("输入字符串中没有找到任何目标字符")
或者用更简洁的列表推导式写法:
sentence = input("Enter input: ") target_letters = {"a", "b", "c"} valid_indices = [sentence.index(c) for c in target_letters if c in sentence] print(min(valid_indices) if valid_indices else "无匹配字符")
方法二:遍历字符串实时跟踪最小索引
这种方法不需要多次调用index,直接遍历字符串的每个字符和对应的索引,一旦遇到目标字符就更新最小索引,效率更高,尤其适合长字符串:
sentence = input("Enter input: ") target_letters = {"a", "b", "c"} min_idx = None for idx, char in enumerate(sentence): if char in target_letters: # 第一次找到目标字符,或者当前索引比已记录的更小 if min_idx is None or idx < min_idx: min_idx = idx if min_idx is not None: print(min_idx) else: print("输入字符串中没有找到任何目标字符")
内容的提问来源于stack exchange,提问作者ashton
相关产品推荐
相关产品推荐

