简体   繁体   中英

Python loop to write across columns in CSV

I'm trying to write a csv as follows: data[0][0] should be in row 1 column A, data[0][1] should be in row 1 column B, data[1][0] should be in row 2 column A, data[1][1] should be in row 2 column B and so on.

If I use something inefficient like the following code, I can write to the csv as intended.

                for i in range(0, len(data)-lg):
                    writer.writerow([data[i][0], data[i][1], data[i][2],...])

I really need something like the following code. But, this code writes everything in Column A. How can I modify it to accomplish my objective? Thanks.

            for i in range(0, len(data)-lg):
                for j in range(0, lg+6):
                    writer.writerow([data[i][j]])

I think the idiomatic way to do this would be as such (not fully understanding your lg variable):

num_cols = lg + 6
for row in data:
    writer.writerow(row[:num_cols])

If you weren't doing any processing on the rows in the loop, you could do it even more concisely:

writer.writerows(data)

Edit 1 Updated based on comment explaining lg variable

why not?

for row in data:
    writer.writerow(row)

writerow() takes a row (sequence of strings or numbers) as input. Your second code passes only one element to writerow() so the element is written in separate row (ie each element in column A). In your first example you do the right thing by passing the entire collection of data row to writerow() so it works. As Dan D. has suggested a more pythonic way is

for x in data:
    writer.writerow(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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