检查值是否存在,并将它们添加到Python中的数组中

时间:2015-08-14 18:03:30

标签: python arrays

这是我的代码(抱歉格式化):

if row[0] == "":
    empty1 = "true"
    print "row[0] needs a Variable"
else:
    print "row[0] has Variable"

if row[1] == "":
    empty1 = "true"
    print "row[1] needs a Variable"
else:
    print "row[1] has Variable"

if row[2] == "":
    empty1 = "true"
    print "row[2] is Missing Variable"
else:
    print "row[2] has Variable"

if row[3] == "":
    empty2 = "true"
    print "row[3] is Missing Variable"
else:
    print "row[3] has Variable" 

if row[4] == "":
    empty3 = "true"
    print "row[4] is Missing Variable"
else:
    print "row[4] has Variable" 

if row[5] == "":
    empty4 = "true"
    print "row[5] is Missing Variable"
else:
    print "row[5] has Variable" 

if row[6] == "":
    empty5 = "true"
    print "row[6] is Missing Variable"
else:
    print "row[6] has Variable" 

if row[7] == "":
    empty6 = "true"
    print "row[7] is Missing Variable"
else:
    print "row[7] has Variable" 

if row[8] == "":
    empty7 = "true"
    print "row[8] is Missing Variable"
else:
    print "row[8] has Variable" 

if row[9] == "":
    empty8 = "true"
    print "row[9] is Missing Variable"
else:
    print "row[9] has Variable" 

if row[10] == "":
    empty9 = "true"
    print "row[10] is Missing Variable"
else:
    print "row[10] has Variable"    

if row[11] == "":
    empty10 = "true"
    print "row[11] is Missing Variable"
else:
    print "row[11] has Variable"    

if row[12] == "":
    empty10 = "true"
    print "row[12] needs a Variable"
else:
    print "row[12] has Variable"    


myList = (row[0], row[1], row[2], row[3], row[12], row[12], row[0], row[12], row[12], row[12], row[0])

print(chunk % (myList))

我尝试做的是遍历.csv文件中的每一行,看看它是否有值。然后,如果它确实有一个值,我想将该行添加到底部的Array,以便它只打印填充的行。我该怎么做?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

迭代数组中的每一行会更容易,如下所示:

myList = []

for i, val in enumerate(row):  #[1]
    if val:                    #[2]
        myList.append(val)
        print 'row[%d] has a value' % i #[3]
    else:
        print 'row[%d] does not have a value' % i #[4]

print myList

让我们打破这段代码,让你学习并了解正在发生的事情。

循环
 在for循环中,在引用#[1] - enumerate()将为您提供列表的元素(在本例中,我们称之为val),以及索引(在此case,我们将它分配给变量i)。

你也可以for val in row:,但我在这里使用了enumerate,所以你打印每行的索引,就像在原始代码中那样。

if语句
引用if的{​​{1}}语句仅使用#[2]。这将检查变量if val:是否具有不是val且不为空的值。这是一种更简洁的方式来编写您最初拥有的null,但它们在逻辑上是相同的。

打印和字符串格式
ref if row[X] != ""中的print语句允许您打印而无需对行进行硬编码。 #[3] and #[4]在数字字符串中充当占位符,然后在字符串和%d运算符之后定义。在这种情况下,我们将变量%放在那里(这是被访问的i的当前索引)。

继续row陈述,我所写的内容与以下内容相同:
print
它只是一点清洁。

还有一种新的建议方法,即python string format()。在这种情况下,你有:
print 'row[' + i + '] has a value'

希望这会有所帮助,如果我过火了,我很抱歉,我认为你是print 'row[{}] has a value"'.format(i)对你的硬编码字符串的新手,并且有很多Python s。如果有任何不清楚的地方,请询问