按照示例的逻辑,这是找到“第一个”匹配箭头并打印其位置的最方便方法。但是,集合的顺序不是先进先出,所以如果你想保持顺序,我建议用列表代替集合来代替箭头列表,这样可以保持顺序。在arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}
def cxn(line, arrowlist):
try:
result = tuple((x, line.find(x)) for x in arrowlist if x in line)[0]
print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))
# Remember in general it's not a great idea to use an exception as
# broad as Exception, this is just for example purposes.
except Exception:
return 0
如果要在提供的字符串(行)中查找第一个匹配项,可以这样做:
^{pr2}$
或者,如果您可以访问标准库,则可以使用运算符.itemgetter为了达到几乎相同的效果并从较少的函数调用中获得效率:from operator import itemgetter
arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}
def cxn(line, arrowlist):
try:
# key first sorts on the position in string then alphanumerically
# on the arrow match (i.e. -> and ->x matched in same position
# will return -> because when sorted alphanumerically it is first)
result = sorted([(x, line.find(x)) for x in arrowlist if x in line], key=(itemgetter(1,0)))[0]
print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))
except Exception:
return 0
***注意:我使用的箭头列表与您的示例稍有不同,只是因为您提供的箭头列表似乎弄乱了默认代码格式(可能是因为引号结束问题)。记住,您可以像这样在字符串前面加上“r”:r"Text that can use special symbols like the escape \and\ be read in as a 'raw' string literal\"。See this question获取有关原始字符串文本的详细信息。在