Python中的简单逻辑错误

时间:2015-07-07 19:25:50

标签: python function csv

为什么CSV输出的第3行没有"hola"

if levels[a] == "3")应确保将其设置为"hola"

感谢您的任何想法或帮助!

#-*- coding: utf-8 -*-
import csv
levels = [["1"], ["2"], ["3"]]
def column1Logic(self):
    self.column1 = "logic worked"
    self.column1 = self.greeting
class Row(object):
    column1 = "name"
    greeting = "oh"
    def __init__(self, level, greeting):
        self.level = level
        self.greeting = greeting
    def rowEntry(self, level, greeting):
        column1Logic(self)
        lol = [[self.column1]]
        lol[0] = self.column1
        file_writer.writerow([o for o in lol])
with open("test.csv", "wb") as test_file:
    file_writer = csv.writer(test_file)
    for a in range(0, len(levels)):
        if levels[a] == "3":
            greeting = "hola"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)
        else:
            greeting = "hi"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)

1 个答案:

答案 0 :(得分:1)

您正在迭代列表列表。因此,您应该检查是否获得['3']而不仅仅是'3'

# -*- coding: utf-8 -*-
import csv
levels = [["1"], ["2"], ["3"]]
def column1Logic(self):
    self.column1 = "logic worked"
    self.column1 = self.greeting

class Row(object):
    column1 = "name"
    greeting = "oh"
    def __init__(self, level, greeting):
        self.level = level
        self.greeting = greeting
    def rowEntry(self, level, greeting):
        column1Logic(self)
        lol = [[self.column1]]
        lol[0] = self.column1
        file_writer.writerow([o for o in lol])

with open("test.csv", "wb") as test_file:
    file_writer = csv.writer(test_file)
    for a in range(0, len(levels)):
        print levels[a]
        if levels[a] == ['3']:  # instead of levels[a] == "3"
            greeting = "hola"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)
        else:
            greeting = "hi"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)