通过递增器和枚举对文本列进行排序

时间:2017-09-06 16:55:55

标签: python list loops text

还有新的使用python和StackOverflow。我试图获取一个带有单词列表的文本文件并对其进行迭代,并将每个第1,第2和第3个单词排序为3个不同的列表。我的问题是我无法让它多次运作。我认为我的增量器可能不正确。

shakey2 = open('/path/to/file/shakey2.txt', 'r')

col1 = []
col2 = []
col3 = [] 
inc = 0
ent1, ent2, ent3 = range(3) #0, 1, 2
for en, line in enumerate(shakey2):
    l = line.strip()
    if ent1 + inc == en:
        col1.append(l)
    elif ent2 + inc == en:
        col2.append(l)
    elif ent3 + inc == en:
        col3.append(l)

    inc += 3
    continue    

shakey2.close()
print(col1, col2, col3)

以下是我正在使用的文本文件的片段:

artless
base-court
apple-john
bawdy
bat-fowling
baggage
beslubbering
beef-witted
barnacle
bootless
beetle-headed
bladder
churlish
boil-brained
boar-pig
cockered
clapper-clawed
bugbear

输出:

(['artless'], ['base-court'], ['apple-john'])

期望的输出:

(['artless', 'bawdy', 'beslubbering'], ['base-court', 'bat-fowling', 'beef-witted'], ['apple-john', 'baggage', 'barnacle'])

1 个答案:

答案 0 :(得分:3)

使用mod,您可以轻松完成:

shakey2 = open('/path/to/file/shakey2.txt', 'r')

cols = [[] for _ in range(3)]
for en, line in enumerate(shakey2):
    cols[en % 3].append(line.strip())

shakey2.close()
print(cols)

如果你想将这个列表解压缩到最初的三个变量中:

col1, col2, col3 = cols