python输出文本 去掉引号_如何从导出的python列表中删除逗号,引号和括号?

1586010002-jmsa.png

You guys were super helpful with my last newbie question so I figured I would give it another shot. Right now, my Python 3 code takes data from a CSV file, stores the data as a list, creates permutations of that data, and exports it back out into a new csv file in a column format. Unfortunately, the format of the exported list is not the best for what I need it for. My question is: How do I remove the commas, brackets, and parenthesis from the exported list in python?

How it Looks Now:

('Hello', 'World', 'How')

('Hello', 'World', 'Are')

('Hello', 'How', 'World')

How I would like it to look:

Hello World How

Hello World Are

Hello How World

Here is the code I am using, does anyone have any advice or suggestions? I am trying to learn so any extra insight would be much appreciated!

import csv

import itertools

with open('/users/Desktop/pythondata.csv', 'r') as f:

reader = csv.reader(f)

J = []

for row in reader:

J.extend(row)

C = list(itertools.permutations(J, 3))

with open('THISISATEST.csv','w')as f:

writer=csv.writer(f,lineterminator='\n')

for val in C:

writer.writerow([val])`

P.S. -- Please forgive me if this is not formatted correctly, I am new to the board!

解决方案

Your question:

I recommend that you just use the join method to get the single string you are looking for. You could try:

with open('test.csv', 'w') as a_file:

for result in C:

result = ' '.join(result)

a_file.write(result + '\n')

Basically, the join method called on a the string ' ' (a single space) will take each item in its argument (a single result from your permutations) and add them together in a single string separated by whatever that first string was (the single space). This site gives a simple, illustrative example.

The join method is called with the syntax '[separator]'.join([list of items to join]), so if you just wanted to mash everything together into one string with no spaces, you could call it on an empty string: ''.join([my list]).

Since you do not need a comma-separated file (CSV), you can simplify things by just using the a_file.write method as shown. If you use the CSV writer in this code you will get commas between every letter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值