使用python编程时在迭代时修改列表 [英] Modifying a list while iterating when programming with python

查看:78
本文介绍了使用python编程时在迭代时修改列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作中使用的程序使用Python作为脚本语言.我试图在插入列表时修改列表感到困惑.另外,我在for循环中有一些逻辑,我想将列表的一部分从浮点数转换为文本.最后,所有文本必须正好为4个空格.在解决该问题的研究中,我遇到了许多其他模拟问题,这些其他问题是试图在迭代列表时尝试修改列表的其他人的.但是我觉得我的问题很独特,因为我试图在遍历列表时将列表从浮点数修改为文本.

A program I'm using at work uses Python as a scripting language. I am perplexed in my attempts to modify a list while interating over it. Also, I have some logic inside the for loop that I would like to convert portions of the list from floats to text. In the end all the text have to be exactly 4 spaces. In my research to solve this problem I have come accross numerous simular problems for other people attempting to modify a list while iterating over it. However I feel my issue is unique because I am attempting to modify the list from floats to text while iterating over it.

我实际上找到了解决该问题的方法,但是我觉得解决方案要复杂得多,因此我需要一个更简单的解决方案,这就是我在这里的原因.我想改进代码.

I actually found a work around for the problem but I feel the solution was more complicated then it needed to be and I'm looking for a more simple solution which is the reason why I'm here. I would like to improve the code.

这是给我带来麻烦的代码:

Here is the code which is giving me problems:

#these come in as floats with a single decimal space, ex:99.9
val = [AvailibilityLine1, AvailibilityLine2,
       PerformanceLine1, PerformanceLine2,
       QualityLine1, QualityLine2]

for i in val:
    j = 0
    if i >= 100:
       val[j] = "100 "                                                           
    elif i >= 10 and i < 100:
       val[j] = str(val)
    elif i > 0 and  i < 10:
       val[j] = " " + str(val)
    elif i <= 0:
       val[j] = "    "    #insert 4 spaces
    else:
       val[j] = "    "    #insert 4 spaces if all else fails
    j=j+1

推荐答案

这应该有效

AvailibilityLine1 = 1.9
AvailibilityLine2 = 45.9
PerformanceLine1 = 76.5
PerformanceLine2 = 99.9
QualityLine1 = 100.0
QualityLine2 = 0.0

#these come in as floats with a single decimal space, ex:99.9
val = [AvailibilityLine1, AvailibilityLine2, PerformanceLine1, 
       PerformanceLine2, QualityLine1, QualityLine2] 

j = 0
for i in val:
    if i >= float(100):
        val[j] = "100 "
    elif i >= 10 and i < 100:
        val[j] = str(val[j])
    elif i > 0 and  i < 10:
        val[j] = " " + str(val[j])
    elif i <= 0:
        val[j] = "    "    #insert 4 spaces
    else:
        val[j] = "    "    #insert 4 spaces if all else fails
    j = j + 1

print val

输出

>>> [' 1.9', '45.9', '76.5', '99.9', '100 ', '    ']

您的代码中的问题:

  1. 计数器J的初始化应该在for循环之外
  2. 您要在if-else的第二和第三条件下将整个列表(val)分配给列表索引

这篇关于使用python编程时在迭代时修改列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆