Simon Lindgren
Simon Lindgren

Reputation: 2031

Iterating over a set of lists, one list at a time

I have the code below. Can "The Loop" be simplified so that I do not have to repeat the statements?

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

Upvotes: 2

Views: 67

Answers (3)

farsil
farsil

Reputation: 1035

The answer by Nessuno is sufficient in this case, but in general you may also want to check the csv.writer class, which provides an unified interface for writing CSV files:

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

Upvotes: 3

Sören Titze
Sören Titze

Reputation: 1005

You could just do:

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

Upvotes: 4

timgeb
timgeb

Reputation: 78650

enumerate the lists, then loop over their items.

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

Upvotes: 0

Related Questions