我是
Python新手,我对列表有困难.我希望从列表中的所有值中减去1,除了值10.5.下面的代码给出了x3列表分配索引超出范围的错误.到目前为止的代码:
- x2=[10.5,-6.36,11.56,19.06,-4.37,26.56,9.38,-33.12,-8.44,0.31,-13.44,- 6.25,-0.94,-5.94,-13.75,-23.44,-51.68,10.5]
- x3=[]
- i=0
- while (i<22):
- if x2[i]==10.5:
- x3[i]=x2[i]
- else:
- x3[i]=x2[i]-1
- break
- #The result I want to achieve is:
- #x3=[10.5,-7.36,10.56,18.06,-5.37,25.56,8.38,-34.12,-9.44,-1.31,-14.44,-7.25,-1.94,-6.94,-14.75,-24.44,-52.68,10.5]
解决方法
请尝试以下方法:
- x3 = [((x - 1) if x != 10.5 else x) for x in x2]