python - 遍历一组列表,一次一个列表

标签 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 in topic2:
    print i
    outfile2.write(i +";2\n")
for i in topic1:
    print i
    outfile2.write(i +";3\n")

最佳答案

你可以这样做:

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

关于python - 遍历一组列表,一次一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811088/

相关文章:

Python 如何仅接受用户输入的某些单词

python - YAML 解析为对象(PyYAML Python3)

python - 在Python中编写一行,最好使用什么数据结构?

c# - 从字符串末尾提取整数

r - 如何将循环的结果存储到变量中?在R中

python - 如何使用 Pandas 为包含特定字符串的单元格中的文本着色

循环遍历大型 numpy 整数数组时 Python 内存溢出,一次性转换

python - 仅适用于列表列表中的前两个列表的函数

javascript - 如何在Sharepoint App中检索Sharepoint列表?

python - PYODBC MS Access 插入错误 - 参数太少