列表理解多行字符串到2D数组

时间:2018-12-31 04:29:38

标签: python arrays string list list-comprehension

我在解决问题时遇到问题。我需要转换以下字符串

meciuri = """Romania 4 - 0 Franta
Italia 2 - 1 Rusia
Franta 3 - 0 Italia
Rusia 2 - 2 Romania
Romania 1 - 0 Italia
Franta 2 - 1 Rusia"""

变成一个二维数组,看起来像这样

meciuri_2darray = [['Romania', '4', '-', '0' ,'Franta'],
['Italia' ,'2' ,'-', '1', 'Rusia'], 
['Franta' ,'3' ,'-' ,'0', 'Italia'], 
['Rusia', '2', '-', '2', 'Romania'],
['Romania', '1' ,'-' ,'0' ,'Italia'],
['Franta' ,'2' ,'-' ,'1' ,'Rusia']]

我尝试了不同的变体,但是我真的是2D数组和列表理解的新手。这是到目前为止我设法做到的,但是结果根本令我不满意

meciuri_2darray = [[i for i in meciuri.split('\n')] for line in meciuri]

输出

[['R'], ['o'], ['m'], ['a'], ['n'], ['i'], ['a'], [' '], ['4'], [' '], ['-'], [' '], ['0'], [' '], ['F'], ['r'], ['a'], ['n'], ['t'], ['a'], ['', ''], ['I'], ['t'], ['a'], ['l'], ['i'], ['a'], [' '], ['2'], [' '], ['-'], [' '], ['1'], [' '], ['R'], ['u'], ['s'], ['i'], ['a'], ['', ''], ['F'], ['r'], ['a'], ['n'], ['t'],
['a'], [' '], ['3'], [' '], ['-'], [' '], ['0'], [' '], ['I'], ['t'], ['a'], ['l'], ['i'], ['a'], ['', ''], ['R'], ['u'], ['s'], ['i'], ['a'], [' '], ['2'], [' '], ['-'], [' '], ['2'], [' '], ['R'], ['o'], ['m'], ['a'], ['n'], ['i'], ['a'], ['', ''], ['R'], ['o'], ['m'], ['a'], ['n'], ['i'], ['a'], [' '], ['1'], [' '], ['-'], [' '], ['0'], [' '], ['I'], ['t'], ['a'], ['l'], ['i'], ['a'], ['', ''], ['F'], ['r'], ['a'], ['n'], ['t'], ['a'], [' '], ['2'], [' '], ['-'], [' '], ['1'], [' '], ['R'], ['u'], ['s'], ['i'], ['a']]

2 个答案:

答案 0 :(得分:3)

您可以使用非嵌套列表理解:

meciuri_2darray = [i.split() for i in meciuri.split('\n')]

# [['Romania', '4', '-', '0', 'Franta'],
#  ['Italia', '2', '-', '1', 'Rusia'],
#  ['Franta', '3', '-', '0', 'Italia'],
#  ['Rusia', '2', '-', '2', 'Romania'],
#  ['Romania', '1', '-', '0', 'Italia'],
#  ['Franta', '2', '-', '1', 'Rusia']]

答案 1 :(得分:2)

import os
meciuri = """Romania 4 - 0 Franta
Italia 2 - 1 Rusia
Franta 3 - 0 Italia
Rusia 2 - 2 Romania
Romania 1 - 0 Italia
Franta 2 - 1 Rusia"""
l=meciuri.split(os.linesep)
print([x.split(" ") for x in l])