如有条件,请替换列表中的项目

时间:2019-01-17 06:06:51

标签: python-2.7

我需要根据负/正值替换列表中的温度值,并同时消除浮点数。即值“ -0.81”应为“ -1”(整数)或“ 0.88”应为“ 1”。

myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in range (len(myList)):
    if myList[i][0] == '-' and int(myList[i][-2]) > 5:
       do sth...

最后,我需要带有新值的新列表。谢谢您的提示。

2 个答案:

答案 0 :(得分:1)

您的代码已经差不多了。不必按索引引用元素。

myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in myList:
    if i[0] == '-' and int(i[-2]) > 5:
       do sth...

如果您要做的只是四舍五入,则可以使用列表理解。

roundlist = [round(float(i)) for i in myList]

答案 1 :(得分:0)

您可以将字符串解析为数字,检查舍入(小数点是大于还是小于0.5),然后将其转换回字符串

<pre><code>
python Chess.py
Enter FEN: 6k1/6pp/1p2p3/p1pN4/4P3/1qP2RPP/6BK/8 w - - 0 1
White to move
Ne7+ eval =  {1: Score(cp=None, mate=2)}
Nc7 eval =  {1: Score(cp=-220, mate=None)}
Nf6+ eval =  {1: Score(cp=-871, mate=None)}
Nxb6 eval =  {1: Score(cp=-753, mate=None)}
Nf4 eval =  {1: Score(cp=-163, mate=None)}
Nb4 eval =  {1: Score(cp=-829, mate=None)}
Ne3 eval =  {1: Score(cp=-424, mate=None)}
Rf8+ eval =  {1: Score(cp=-1198, mate=None)}
Rf7 eval =  {1: Score(cp=-1174, mate=None)}
Rf6 eval =  {1: Score(cp=-1097, mate=None)}
Rf5 eval =  {1: Score(cp=-1042, mate=None)}
Rf4 eval =  {1: Score(cp=-604, mate=None)}
Re3 eval =  {1: Score(cp=-500, mate=None)}
Rd3 eval =  {1: Score(cp=-527, mate=None)}
Rf2 eval =  {1: Score(cp=-613, mate=None)}
Rf1 eval =  {1: Score(cp=-672, mate=None)}
Kh1 eval =  {1: Score(cp=-703, mate=None)}
Kg1 eval =  {1: Score(cp=-679, mate=None)}
Bh1 eval =  {1: Score(cp=-684, mate=None)}
Bf1 eval =  {1: Score(cp=-723, mate=None)}
e5 eval =  {1: Score(cp=-837, mate=None)}
h4 eval =  {1: Score(cp=-537, mate=None)}
g4 eval =  {1: Score(cp=-662, mate=None)}
c4 eval =  {1: Score(cp=800, mate=None)}
</code></pre>