我有一个字符串列表.
theList = ['a', 'b', 'c']
我想在字符串中添加整数,产生如下输出:
newList = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
我想将此格式保存为.txt文件,格式如下:
a0
b0
c0
a1
b1
c1
a2
b2
c2
a3
b3
c3
尝试:
theList = ['a', 'b', 'c']
newList = []
for num in range(4):
    stringNum = str(num)
    for letter in theList:
        newList.append(entry+stringNum)
with open('myFile.txt', 'w') as f:
    print>>f, newList
现在我可以保存到文件myFile.txt,但文件中的文本为:
['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
有关更多pythonic方法实现我的目标的任何提示都是非常受欢迎的,
而不是你的最后一行,使用:
f.write("\n".join(newList))
这将把newList中的字符串写成f,用换行符分隔.请注意,如果您实际上不需要newList,则可以组合两个循环并随时编写字符串:
the_list = ['a', 'b', 'c']
with open('myFile.txt', 'w') as f:
    for num in range(4):
        for letter in the_list:
            f.write("%s%s\n" % (letter, num))