简体   繁体   English

将字符串重新排列为二维数组python

[英]Rearrange string into 2D array python

I have the following string after using urllib:使用 urllib 后,我有以下字符串:

459,2277,617459268\n14619,99,19600737\n11297,99,18666551\n16603,99,19761406\n12660,99,28741324\n4543

after using replace and split:使用替换和拆分后:

data = data.replace('\\n', ',').split(',')

['459', '2277', '617459268', '14619', '99', '19600737', '11297', '99', '18666551', '16603', '99', '19761406', '12660', '99', '28741324', '4543']

However, I had like to get the following 2D array:但是,我想获得以下二维数组:

459 2277 617459268
14619 99 19600737
11297 99 18666551...

Is there a way to break this 1D array into a 2D array without using numpy ?有没有办法在不使用numpy情况下将此一维数组分解为二维数组?

When I say 2D array I mean column list when each row is 1x3 list.当我说 2D 数组时,我的意思是每行是 1x3 列表时的列列表。

Easy ways will be appreciated.简单的方法将不胜感激。

Thank you.谢谢你。

Don't replace your "row delimiters" by "column delimiters".不要用“列分隔符”替换“行分隔符”。 Instead, for split the string on the row delimiter.相反,用于拆分行分隔符上的字符串。 Then split each row on the column delimiter.然后在列分隔符上拆分每一行。

If your input has new line characters:如果您的输入有换行符:

rows = data.split()

If your input has a literal backslash followed by the letter n rather than a newline character:如果您的输入有一个文字反斜杠后跟字母n而不是换行符:

rows = data.split('\\n')

Either way, now you can split each row on commas:无论哪种方式,现在您都可以用逗号分割每一行:

matrix = [row.split(',') for row in rows]

save this str to string like s then :将此 str 保存到像 s 这样的字符串然后:

s='''459,2277,617459268\n14619,99,19600737\n11297,99,18666551\n16603,99,19761406\n12660,99,28741324\n4543'''

for i in s.split('\n'):
    print (i)


459,2277,617459268
14619,99,19600737
11297,99,18666551
16603,99,19761406
12660,99,28741324
4543

or if you want to print without , :或者,如果您想在没有,情况下打印:

for i in s.replace(',' , ' ').split('\n'):
    print (i)


459 2277 617459268
14619 99 19600737
11297 99 18666551
16603 99 19761406
12660 99 28741324
4543

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

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