简体   繁体   English

从文件创建列表

[英]Creating a list from a file

I'm creating a horoscope where I have a file with different qualities and 4-5 sentences with different statements regarding each quality. 我正在创建一个占星术,其中有一个具有不同质量的文件,以及4-5个句子,其中每种质量都有不同的说明。 The qaulities are separated with a blank line. 质量用空行分隔。 I want to save them into a list called qualities, where qualities[0] contains the sentences regaring the first quality, qualities[1] contains the sentences regarding the second and so on. 我想将它们保存到一个名为quality的列表中,其中quality [0]包含具有第一品质的句子,quality [1]包含与第二品质有关的句子,依此类推。

My code: 我的代码:

class Horoscope:

    def __init__(self, filename):
        self.qualities = list()
        file = open(filename, 'rU')
        i = 0
        for line in file:
            row= line.strip().split('/')
            if len(row) >= 2:
                self.qualities[0+i] = row
            else:
                i += 1
        file.close() FILENAME= 'horoscope.txt'

horoscope= Horoscope(FILENAME)

print(horoscope.qualities)

Unfortunally, all that is printed is "[ ]"... Does anyone know why? 不幸的是,所有打印的都是“ []”……有人知道为什么吗? Thanks! 谢谢!

I'm surprised self.qualities[i] did not raise an IndexError. 我很惊讶self.qualities[i]没有引发IndexError。 That suggests that len(row) is never >= 2 . 这表明len(row)从不>= 2 However, if it were, you should use append instead: 但是,如果是这样,则应改为使用append

class Horoscope:
    def __init__(self, filename):
        self.qualities = list()
        with open(filename, 'rU') as f:
            for line in f:
                row = line.strip().split('/')
                if len(row) >= 2:
                    self.qualities.append(row)

FILENAME= 'horoscope.txt'
horoscope= Horoscope(FILENAME)
print(horoscope.qualities)

Note that this does not replicate the logic of your original code. 请注意,这不会复制原始代码的逻辑。 It appends every row for which len(row) >= 2 . 它附加len(row) >= 2每一行。 You original code does something more complicated, sometimes overwriting at the same index, sometimes advancing the index. 您的原始代码会做一些更复杂的事情,有时覆盖相同的索引,有时会使索引前进。 Do you really want that? 你真的想要那个吗? If so, what do you want to place in the list at the locations where the index is simply advanced? 如果是这样,您想在列表中简单索引的位置放置什么? None ? None Something value have to be placed at every index... (You can't have a list with values only at, say, the second and fifth index. A list of length 5 has to have 5 values.) 必须在每个索引处放置一个值...(不能有仅在第二和第五个索引处具有值的列表。长度为5的列表必须具有5个值。)

It almost looks like your code could be simplified to: 看起来您的代码可以简化为:

class Horoscope:
    def __init__(self, filename):
        with open(filename) as fin:
            self.qualities = [line.strip() for line in fin if '/' in line]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM