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

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']]

最佳答案

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

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']]

关于python - 列表理解多行字符串到2D数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53983588/

10-08 20:35