[英]splitting python 1d array into 2d array by comma
I'm relatively new to python (experience in c#), and I have a list in a text file that I dumped into a list using; 我是python的新手(在c#中的经验),并且在文本文件中有一个列表,我使用它将其转储到列表中。
with open(fname) as f:
content = f.readlines()
content = [x.strip() for x in content]
The thing is, every line is in the form XXXXX, XXXXX (with varying lengths of XXXXX), and I want to convert f into a 2-dimensional array with things in the line before the comma in the first dimension and everything after in the second. 事实是,每一行的格式为XXXXX,XXXXX(长度各不相同的XXXXX),我想将f转换为二维数组,其中第一维的逗号之前的行中的内容以及第二。
What's the best practice for doing something like that? 做这样的事情的最佳实践是什么?
.split(',')
: .split(',')
: From the documentation, we can see that the string
method .split
will: 从文档中,我们可以看到
string
方法.split
将:
Return a list of the words in the string, using sep as the delimiter string.
使用sep作为分隔符字符串,返回字符串中单词的列表。
So to give an example, taking the string
: 因此,举个例子,使用
string
:
s = "abcd, efgh"
then we can do: 然后我们可以做:
s.split(', ')
to get a list
: 得到一个
list
:
['abcd', 'efgh']
So for your application, just throw it in the list-comprehension
: 因此,对于您的应用程序,只需将其放入
list-comprehension
:
with open(fname) as f:
content = f.readlines()
content = [x.strip().split(', ') for x in content]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.