Reputation: 2031
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
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
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
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