Skip to main content
 首页 » 编程设计

python之使用其他变量的相应值将列表中的变量单独写入表中

2025年05月04日9lovecherry

好的,我的代码如下:

for shidx in xrange(0, book.nsheets): 
print shidx 
sheet = book.sheet_by_index(shidx) 
d = sheet.col_values(0,2) 
D = sheet.col_values(1,2) 
dim = sheet.row_values(0,2) 
if shidx == 0: 
    #numLine = sheet.row_values(2) 
    rs = sheet.col_values(6,2) 
    for i in range(4): 
        BB = sheet.col_values(2 + i, 2) 
        if BB != 0: 
            #print repr(d).rjust(2), repr(D).rjust(3), repr(BB).rjust(4), repr(rs).rjust(5) 
            file = open("C:\\calcul\\SimX18_VitesseLimite\\Documents\\ncapa-20111116\\ncapa\\resources\\output.txt", "w") 
            #file.write(str(table) + '\n') 
            file.write(str(d) + '\n') 
            file.write(str(D) + '\n') 
            file.write(str(BB) + '\n') 
            file.write(str(dim) + '\n') 
            file.write(str(rs) + '\n') 
            file.close() 

由于我一直在尝试一些不同的事情,所以我在最后注释掉了打印品。

我的目标是写入一个文本文件,其中每一行对应于表中的一列。 我的问题是将列表拆分为 d、D、dim 和 BB。这是我想做的:

dim的ROW和d的COLUMN:

dim = [17.0, 27.0, 37.0, 47.0, u'17-47'] (see table below for the first row and to what it corresponds) 
d = [0.59999999999999998, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 15.0, 17.0, 20.0, 22.0, 25.0, 28.0, 30.0, 32.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0, 105.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0] 

1

以及BB的第一行和第二行:

BB = [0.8, 0.0, 0.0, 0.0] BB = [1.0, 0.0, 0.0, 0.0]

我希望能够写入文本文件(相当于下表):

2

但是对于 BB 的第三行:

BB = [1.0, 0.0, 1.8, 0.0]

我需要能够获得以下内容(即有两个“dim”选项):

3

当我说 BB 不等于 0.0 时,我希望能够将 d、D、BB 和 dim 的单个值写入表中,但我无法摆脱所有列表。 .

我真的希望这对某些人有意义,因为我有点卡住了!

请您参考如下方法:

您的要求在多次阅读后最终可以确定。但是您的代码有几个问题:

显示的缩进是拙劣的。大概您正在编辑器中使用选项卡。不要对 Python 源文件这样做。将其设置为每个缩进级别使用 4 个空格。

您正在遍历工作表但忽略了除第一张工作表之外的所有工作表;为什么?

您正在使用 d、D 和 rs 来引用值列表,但不迭代列表。

即使 d 按照它应该的方式引用标量,执行 file.write(str(d) + '\n') 等也无法实现您的目标每行 5 个值的文件的目标。

如果以追加模式打开,则每个输出行打开/关闭一次输出文件将非常低效,并且在写入模式下打开时效率非常低且完全错误 - 您只会写入最后一行.

您需要考虑一下谁/什么将读取/使用您的输出文件,以及他们/它喜欢的格式。

够了。这是你应该做的(伪代码):

open your workbook 
open your output file 
for each sheet: 
    get dim # a list 
    for each data row: 
        get d, D, and rs # three scalars 
        for each bb value in the BB zone of the current row: 
            if bb is non-zero: 
                get the corresponding dim value (e.g. 27) 
                write d, D, bb, dim_value, rs as 1 line to the output file 
close your output file