如果我有这个变量
operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"
如何在`运算符中返回"&"
和"X"
的位置?我需要这样的输出:
1:0, 3:2, 6:4 #1 for "&", 3 for "->", 6 for "X" inside expression variable. #0 for "&", 2 for "->", 4 for "X" inside operator List.
答案 0 :(得分:4)
operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"
print(operator.index("<->"))
这将显示输出:
3
这是你想要的吗?
答案 1 :(得分:1)
operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"
resultString = ''
for one_op in operator: # for each character in your list
startingIndex = expression.find(one_op) # important: assuming it appears only once, find() takes the first occurrence and returns the index
if startingIndex is not -1: # if find() does not find an occurence, it will return -1
resultString += (str(startingIndex) + ':' + str(operator.index(one_op)) + ',') # only that exist is considered
print(resultString.rstrip(','))
输出:
1:0,3:2,6:4