Python 迭代一组列表,每次迭代一个列表

Python 迭代一组列表,每次迭代一个列表,python,list,Python,List,我有下面的代码。“循环”是否可以简化,以便我不必重复这些语句 topic1 = ["abc", "def"] topic2 = ["ghi", "jkl", "mno"] topic3 = ["pqr"] outfile = open('topics_nodes.csv', 'w') outfile.write("Node;Topic\n") # The Loop for i in topic1: print i outfile2.write(i +";1\n") for i

我有下面的代码。“循环”是否可以简化,以便我不必重复这些语句

topic1 = ["abc", "def"]
topic2 = ["ghi", "jkl", "mno"]
topic3 = ["pqr"]

outfile = open('topics_nodes.csv', 'w')
outfile.write("Node;Topic\n")

# The Loop
for i in topic1:
    print i
    outfile2.write(i +";1\n")
for i in topic2:
    print i
    outfile2.write(i +";2\n")
for i in topic1:
    print i
    outfile2.write(i +";3\n")

枚举列表

>>> for i, li in enumerate((topic1, topic2, topic3), 1):
...     for x in li:
...         print(x, i)
... 
abc 1
def 1
ghi 2
jkl 2
mno 2
pqr 3
你可以这样做:

for index, topic_list in enumerate([topic1, topic2, topic3], 1):
    for i in topic_list:
        print i
        outfile2.write('{:d};{:d}\n'.format(i, index))

在这种情况下,Nessuno给出的答案就足够了,但一般来说,您可能还需要检查该类,该类为编写CSV文件提供了统一的接口:

import csv

with open('topics_nodes.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=';')
    writer.writerow(('Node', 'Topic'))

    for topic, nodes in enumerate([topic1, topic2, topic3], 1):
        for node in nodes:
            print node
            writer.writerow((node, topic))

缺少半彩色
它还故意丢失了文件I/O,因为这不是问题的一部分。这是最清晰的答案,但我相信像这样使用
格式
更可读:
outfile2.write('{:d};{:d}\n'.format(I,index))
。或者只是使用串联列表作为
索引,枚举中的lst(主题1+主题2+主题3,1):
保存内部循环。同时尽量避免使用
list
作为变量name@Anzel当我没有可靠的IDE向我指出这种“否”时,会发生这种情况。我会立即更改它。但是我需要外部循环的索引来知道要将哪个索引写入文件。如果需要外部循环的索引,则可以完全有道理:)