根据金字塔的形状进行Python打印

时间:2018-05-25 08:53:34

标签: python

我的csv数据喜欢这个: enter image description here

我使用此代码进行打印:

import pandas as pd
import csv
rs = pd.read_csv(r'D:/Clustering_TOP.csv',encoding='utf-8')
with open('D:/Clustering_TOP.csv','r') as csvfile:
    reader = csv.reader(csvfile)
    rows = [row for row in reader]
csv_title = rows[0]
csv_title = csv_title[1:]
len_csv_title = len(csv_title)
for i in range(len_csv_title):
    for j in range(i,len_csv_title):
        print(str(rs[csv_title[i]].corr(rs[csv_title[j]])), end='\t')
    print()

打印结果是这样,格式不对: enter image description here

但事实上,我希望打印像金字塔一样,例如: enter image description here

如何修改我的代码?

5 个答案:

答案 0 :(得分:1)

你好我不是100%肯定,但我认为你的第二个是问题。试试这个:

for i in range(len_csv_title):
    for j in range(i+1):
        print(str(rs[csv_title[i]].corr(rs[csv_title[j]])), end='\t')
    print()

答案 1 :(得分:0)

我认为问题在于你的第二个' for'环。范围应为for j in for j in range(len_csv_title),而不是range(i,len_csv_title)

答案 2 :(得分:0)

更改以下行:

for j in range(i,len_csv_title):

为:

for j in range(0,i+1):

答案 3 :(得分:0)

这是一个以您请求的模式打印开始的示例代码

def pyramidpattern(n):
  for i in range(0, n):
    for j in range(0, i+1):
      print("* ",end="")
    print("\r")

n=5
pyramidpattern(n)

输出:

* 
* * 
* * * 
* * * * 
* * * * * 

答案 4 :(得分:0)

您需要在代码中使用反向循环。只需更改for循环就可以了。

import pandas as pd
import csv
rs = pd.read_csv(r'file',encoding='utf-8')
with open('file','r') as csvfile:
    reader = csv.reader(csvfile)
    rows = [row for row in reader]
csv_title = rows[0]
csv_title = csv_title[1:]
len_csv_title = len(csv_title)

for i in range(len_csv_title):
    for j in range(0,i+1):
        print(str(rs[csv_title[i]].corr(rs[csv_title[j]])), end='\t')
    print()
  

尝试更改for循环   表示范围内的j(0,i + 1):