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

时间:2017-03-15 13:23:05

标签: python list

我有以下代码。可以" The Loop"简化,以便我不必重复这些陈述?

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")

3 个答案:

答案 0 :(得分:4)

你可以这样做:

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))

答案 1 :(得分:3)

在这种情况下,Nessuno的答案已足够,但一般情况下,您可能还需要查看csv.writer类,该类提供了用于编写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))

答案 2 :(得分:0)

enumerate列表,然后遍历他们的项目。

>>> 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