简体   繁体   English

更改列表的最后一个元素也会覆盖倒数第二个元素

[英]Changing the last element of a list also overwrites the second last element

I have a csv-file along the following structure:我有一个遵循以下结构的 csv 文件:

1 start,end,ID
2 int1,int2,string1
3 int3,int4,string2
4 int5,int6,string3
5 int7,int8,string4

My goal is to create a new csv that writes a unique row for, first, the end value and, second, the start value as an end value.我的目标是创建一个新的 csv 写入一个唯一的行,首先是结束值,其次是开始值作为结束值。

1 start,end,ID
2 int1,int2,string1
3 ,int1,string1
4 int3,int4,string2
5 ,int3,string2

I attempted this by writing the input csv in a list and iterating through that list.我通过在列表中写入输入 csv 并遍历该列表来尝试此操作。 For each row, two new rows are appended in the output list.对于每一行,在 output 列表中追加两个新行。 After appending the second row, respectively, the end value was set to the start value of the input list.在分别附加第二行之后,将结束值设置为输入列表的开始值。 The following is the code that I used:以下是我使用的代码:

import csv

with open(r"input path") as csv_sbw, open("output path","wb") as csv_new:
    csv_in = csv.reader(csv_sbw)
    csv_out = csv.writer(csv_new)
    fields_out = [[]] #list for the output csv
    fields = list(csv_in) #list for the input csv
    fields_out[0] = fields[0] #headline is taken from the input
    fields[0].append("m_value")
    for row in fields[1:]:
        row.append(1)
        if row[2].isdigit() == False and len(row[2]) == 16 and row[2][0] != 0 and row[0] != '' and row[0] != '0' and row[1] != '0': #invalid rows are skipped
            fields_out.append(row) #first row is appended
            fields_out.append(row) #second row is appended
            fields_out[-1][1] = row[0] #the start value of the last appended row is set as an end value
            fields_out[-1][0] = '' #start field of last appended row is deleted
            fields_out[-1][3] = 0
    csv_out.writerows(fields_out) #output csv is written

Instead of producing a csv along the example described above, I get the following result:我没有按照上述示例生成 csv,而是得到以下结果:

1 start,end,ID,m_value
2 1032,1032,'A',0
3 1032,1032,'A',0
4 613,613,'B',0
5 613,613,'B',0

So, by changing fields[-1] the code seems to overwrite the second last appended row, as well.因此,通过更改fields[-1]代码似乎也覆盖了倒数第二行。 As far as I understand, appending two values in a row to a list creates two new list elements of which only the last appended value would be returned if I requested list[-1] .据我了解,将一行中的两个值附加到列表会创建两个新的列表元素,如果我请求list[-1] ,则只会返回最后一个附加值。 How do I prevent the code from overwriting both appended rows and instead let it overwrite only the last appended row?如何防止代码覆盖两个附加的行,而是让它只覆盖最后附加的行?

To restate your objective, the snippet below creates a new csv that为了重申您的目标,下面的代码片段创建了一个新的 csv

  1. writes a row for the original line and,为原始行写入一行,并且,
  2. writes a row with the start value and the string.用起始值和字符串写入一行。

If that assessment is valid, I usually open one file at a time to minimize my cognitive burden.如果该评估有效,我通常一次打开一个文件以最大程度地减少我的认知负担。

with open('input.csv','r') as file_handle:
    file_content = file_handle.read().split('\n')
with open('output.csv','r') as file_handle:
    for index,line in enumerate(file_content):
        if index==0:
            print(line)
            file_handle.write(line)
        else:
            line_as_list = line.split(',')
            print(line_as_list)
            file_handle.write(line)
            print(line_as_list[0], line_as_list[-1])
            file_handle.write(str(line_as_list[0])+","+str(line_as_list[-1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM