使用三元运算符的列表理解import mathmyList = [2, '+', 3, 'pi']myList = [x if x != 'pi' else math.pi for x in myList]print(myList)解释在 python 中,可以使用其他列表创建列表,这称为列表理解。[f(x) for x in list]f(x) - some function of xfor x in list - passing over each element in the listWrapped in square brackets to represent a new list being created.此外,python 有一个看起来有点傻的三元“运算符”:example = x if x != 'pi' else math.pi这是一个表达式(在 Python 中,这意味着它需要被评估并有一个值),如果 x 不是'pi',example 将等于 x,否则它将等于 math.pi。它相当于:if x != 'pi': example = xelse: example = math.pi