我有以下代码:
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
Run Code Online (Sandbox Code Playgroud)
基本上,我计算一个新索引并使用它来从列表中查找一些元素.为了确保索引在列表的边界内,我需要将这两个if
语句写成4行.那是相当冗长,有点难看......我敢说,这是非常不科幻的.
还有其他更简单,更紧凑的解决方案吗?(和更多pythonic)
是的,我知道我可以if else
在一行中使用,但它不可读:
new_index = 0 if new_index < 0 else len(mylist) - 1 if new_index >= len(mylist) else new_index
Run Code Online (Sandbox Code Playgroud)
我也知道我可以链max()
和min()
在一起.它更紧凑,但我觉得它有点模糊,如果我输错了就更难找到错误.换句话说,我觉得这很简单.
new_index = max(0, min(new_index, len(mylist)-1))
Run Code Online (Sandbox Code Playgroud) 我正在编写一个python函数来执行以下操作,从每行添加数字,这样我就可以找到平均值.这是我的文件的样子:
-2.7858521
-2.8549764
-2.8881847
2.897689
1.6789098
-0.07865
1.23589
2.532461
0.067825
-3.0373958
Run Code Online (Sandbox Code Playgroud)
基本上我已经编写了一个程序,为每一行执行for循环,递增行的计数器并将每一行设置为浮点值.
counterTot = 0
with open('predictions2.txt', 'r') as infile:
for line in infile:
counterTot += 1
i = float(line.strip())
Run Code Online (Sandbox Code Playgroud)
现在是我被困的部分
totalSum =
mean = totalSum / counterTot
print(mean)
Run Code Online (Sandbox Code Playgroud)
正如你可以告诉我新的python,但我发现它非常方便文本分析工作,所以我进入它.
额外功能
我还在研究一个额外的功能.但应该是如上所述的单独功能.
counterTot = 0
with open('predictions2.txt', 'r') as infile:
for line in infile:
counterTot += 1
i = float(line.strip())
if i > 3:
i = 3
elif i < -3:
i = -3
Run Code Online (Sandbox Code Playgroud)
从代码中可以看出,函数决定一个数字是否大于3,如果是,则将其设为3.如果number小于-3,则使其为-3.但我试图将其输出到一个新文件,以便它保持其结构.对于这两种情况,我想保留小数位.我总是可以自己舍入输出数字,我只需要完整的数字.
def boundThis(x):
min = 20
max= 100
boundX = int(x)
if (boundX > max):
boundX = boundX % max + min-1
if (boundX > max):
boundX-=max-1
else:
while(boundX < min):
boundX += max-min
return boundX
Run Code Online (Sandbox Code Playgroud)
我试图在两个数字之间绑定x,20和100(不包括).也就是说,一旦达到100,就应该回到20.
我得到它如何与while循环一起工作,(虽然boundX <min)但是我遇到了模数运算符的问题,并用它编写了正确的表达式.
防爆.boundThis(201)应该给我21,并且boundThis(100)给我20.