格式化并在文件中打印列表

时间:2015-03-29 16:44:34

标签: python list file

我有一个列表,里面有一些坐标,当我打印它时:

for i in range(0,len(List)):
    print("".join(["(%d, %d) \n" % (y[i], y[i+1]) for y in (List)]))

输出是这样的:

(0, 3) 
(0, 2) 
(0, 1) 
(1, 1) 
(1, 2) 
(2, 2) 
(2, 1) 
(3, 1) 
(3, 0) 
(2, 0) 
(1, 0) 
(0, 0)

我想将输出保存在.txt中,但这不是问题,我的问题是.txt必须像这样格式化:

(0, 3), (0, 2)
(0, 2), (0, 1)
(0, 1),(1, 1)
(1, 1),(1, 2)
(1, 2),(2, 2)
.....

我尝试过很多东西,但没有任何效果...... 它一定很容易,但我是python的新手 提前谢谢你

5 个答案:

答案 0 :(得分:3)

这就是诀窍:

l = [(0, 3), (0, 2), (0, 1), (1, 1), (1, 2), (2, 2)]

for i in range(0, len(l), 2):
    print(', '.join([str(l[i]), str(l[i+1])]))

# (0, 3), (0, 2)
# (0, 1), (1, 1)
# (1, 2), (2, 2)

答案 1 :(得分:1)

您可以使用zip

mylist = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
# That doesn't have to be the numbers though, you can use your own.

for a, b in zip(mylist, mylist[1:]):
    print("{}, {}".format(a, b), file = myfile) # Will print to myfile.

假设您正在打印到打开的文件。如果您不想在其他任何地方打印,请保留file参数,但默认屏幕。

myfile.txt中的

(0, 0), (0, 1)
(0, 1), (0, 2)
(0, 2), (1, 0)
(1, 0), (1, 1)
(1, 1), (1, 2)
(1, 2), (2, 0)
(2, 0), (2, 1)
(2, 1), (2, 2)    

输出是元组,而不是列表。

答案 2 :(得分:0)

嗯,除了使用索引播放的其他答案外,您还可以使用zip

for a, b, c, d in zip(List, List[1:], List[2:], List[3:]):
    print('({}, {}), ({}, {})'.format(a, b, c, d))

答案 3 :(得分:0)

关于预期产出:

l = [(0, 3), (0, 2), (0, 1), (1, 1), (1, 2), (2, 2)]

for i,j in zip(l,l[1:]):
    print str(i) + "," + str(j) # or print ",".join([str(i),str(j)])

#output
(0, 3),(0, 2)
(0, 2),(0, 1)
(0, 1),(1, 1)
(1, 1),(1, 2)
(1, 2),(2, 2)

如果你想要2个元素的列表分块,试试这个

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]


for i,j in list(chunks(l,2)):
    print ",".join([str(i),str(j)])

#output
(0, 3),(0, 2)
(0, 1),(1, 1)
(1, 2),(2, 2)

答案 4 :(得分:-2)

您的代码:

for i in range(0,len(List)):
    print("".join(["(%d, %d) \n" % (y[i], y[i+1]) for y in (List)]))

将其转换为列表comp。

t = ["".join(["(%d, %d) \n" % (y[i], y[i+1]) for y in (List)]) for i in range(0,len(List))]

(相当于)

s = []
for i in range(0,len(List)):
    s.append("".join(["(%d, %d) \n" % (y[i], y[i+1]) for y in (List)]))

然后:

first = True
other = None
r = ""
for i in t:
    if not first:
        r += other+", "+i+"\n"
        first = True
    else:
        other = i
        first = False
f = open("out.txt","w")
f.write(t)
f.close() #go to notepad