对于此列表理解中的以下 if 语句,要在
person == 'sha'
时创建字符串“sha me”,它会产生错误。 似乎对于列表推导式,只有 if 语句的 else 部分可以包含操作。 我可以重写为 for 循环/if 语句并操作 when person == 'sha'
,但我不清楚为什么它在列表理解中不被接受?
people = ['sha','john','erin']
newlist = [person if person == 'sha' person + ' me' else person + ' Lastname' for person in people]
print(newlist)
产生:
语法错误:“if”表达式后需要“else”
people = ['sha','john','erin']
newlist = [person + ' me' if person == 'sha' else person + ' Lastname' for person in people]
print(newlist)
或者你可以这样使用f-string:
newlist = [f'{person} me' if person == 'sha' else f'{person} Lastname' for person in people]