【发布时间】:2012-04-28 01:05:30
【问题描述】:
我有一个字符串列表。
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 方法的提示,
【问题讨论】:
-
回答者,请注意,OP 要求提供“更 Pythonic”的解决方案,而不是更短或更复杂的解决方案。