我有这些代码行创建一个列表(其中包含不同数量的变量),并希望将它们放在outfile中。事情在
outfile.write('%i ?????' % (bn, crealines[bn]))
由于输出数量不同,我不知道如何编写格式。 无论如何都要输出具有不同列数的输出?
*我看了这个:Increasing variables and numbers by one each time (python) ...但在我的情况下,他们并没有一个一个地增加。 另外,我可以打印没有括号的列表吗?
代码是这样的:
(#在这种情况下,我正在创建一个“立方体” - 矩阵 - 3x3x3)
nx = ny = nz = 3
vec = []
crealines = []
outfile = open('test.txt', 'a')
for bn in arange(nx*ny*nz):
vec = neighboringcubes(bn,nx,ny,nz) #this is a defined function to see which cubes are neighbors to the cube "bn"
crealines.append(vec)
print bn, crealines[bn]
outfile.write('%i, %i ....' % (bn, crealines[bn]))
outfile.close()
使用打印它给了我(这是正确的):
0 0 0 <---- this is the output from function neighboringcubes() -which I don't need-
0 [1, 3, 9] <---- THIS IS WHAT I WANT WRITTEN IN THE OUTPUTFILE
1 0 0
1 [2, 0, 4, 10]
2 0 0
2 [1, 5, 11]
0 1 0
3 [4, 6, 0, 12]
1 1 0
4 [5, 3, 7, 1, 13] <--- BUT YOU CAN SEE IT CHANGES
2 1 0
5 [4, 8, 2, 14]
0 2 0
6 [7, 3, 15]
1 2 0
7 [8, 6, 4, 16]
2 2 0
8 [7, 5, 17]
0 0 1
9 [10, 12, 18, 0]
1 0 1
10 [11, 9, 13, 19, 1]
...
我希望outfile在第一列中包含多维数据集的编号,以及以下列 - 从低到高 - 邻居;像这样:
0 1 3 9
1 0 2 4 10
2 1 5 11
3 0 4 6 12
4 1 3 5 7 13
5 2 4 8 14
6 3 7 15
7 4 6 8 16
8 5 7 17
9 0 10 12 18
...
答案 0 :(得分:1)
您的问题对我来说并不是很清楚,但我相信您希望按排序顺序打印变量bn
后跟其邻居。如果是这样,此代码段说明了如何执行此操作:
>>> bn = 5
>>> neighbors = [10, 12, 2, 4]
>>> print bn, ' '.join(map(str, sorted(neighbors)))
这导致此输出:
5 2 4 10 12
答案 1 :(得分:1)
很少有提议,取决于你想要的东西(现在它们是相同的,但根据数据可能会有不同的表现):
bn = 5
neighbours = [8, 12, -1, 4]
print "{} [{}]".format(bn, ', '.join(map(str, sorted(neighbours))))
print bn, repr(sorted(neighbours))
print bn, str(sorted(neighbours))
输出:
5 [-1, 4, 8, 12]
5 [-1, 4, 8, 12]
5 [-1, 4, 8, 12]
答案 2 :(得分:0)
我知道你可以使用print bn, crealines[bn].sort()
,但我可能错了。 (那是因为我无法测试你的代码。函数arange从哪里导入?)
答案 3 :(得分:0)
谢谢@jaime!
这解决了格式问题:
print&#34; {} {}&#34; .format(bn,&#39;&#39; .join(map(str,crealines [bn])))
我使用vec = sorted(邻居)对邻居进行了排序,然后crealines [bn]已经排序。
输出看起来像这样
5 2 4 8 14