Python中如何传递列表值作为索引切片的位置参数?
问题解决
错误原因
- 不能直接把坐标列表(比如
[10,24])作为字符串的索引传入,Python字符串的切片语法为字符串[起始索引:结束索引],需要单独取出坐标列表里的两个整数值构造切片,而非直接传入整个列表 - 测试代码的参数传递逻辑存在错误:循环遍历
coordinates时直接传了索引值x,没有取出对应位置的坐标列表;额外测试调用里的x、health_questions也属于未定义变量
可运行实现方案
单坐标处理版本
适配你需要逐次调用的场景:
txt = "who makes bromocriptinei am wondering what company makes the drug bromocriptine, i need it for a mass i have on my pituitary gland and the cost just keeps raising. i cannot ever buy a full prescription because of the price and i was told if i get a hold of the maker of the drug sometimes they offer coupons or something to help me afford the medicine. if i buy 10 pills in which i have to take 2 times a day it costs me 78.00. and that is how i have to buy them. thanks." coordinates = [[10, 24], [66, 79]] def string_to_find(coord, txt): # 拆解坐标的起始、结束值构造切片 start, end = coord return txt[start:end] # 遍历调用的两种正确写法 # 写法1:直接遍历坐标列表元素 for coord in coordinates: word_match = string_to_find(coord, txt) print(word_match) # 写法2:按索引遍历(适配你原有的逻辑) for x in range(len(coordinates)): word_match = string_to_find(coordinates[x], txt) print(word_match)
运行后输出结果和你初始的手动切片结果完全一致:
bromocriptinei bromocriptine
批量处理版本
如果需要一次性返回所有坐标对应的切片结果,可以直接用列表推导式实现,代码更简洁:
def batch_string_find(coords_list, txt): return [txt[start:end] for start, end in coords_list] result = batch_string_find(coordinates, txt) print(result) # 输出:['bromocriptinei', 'bromocriptine']
扩展说明
如果后续需要支持带步长的切片,只需要把坐标调整为3个元素的列表[起始, 结束, 步长],函数里对应拆解即可,不需要改动核心逻辑。
内容的提问来源于stack exchange,提问作者Lui Hellesoe
相关产品推荐
相关产品推荐

