【问题标题】:Is there a more efficient way to create this 2D list?有没有更有效的方法来创建这个 2D 列表?
【发布时间】:2014-04-04 07:29:31
【问题描述】:

我正在接收一个包含多行字符的文件,如下所示:

oeoeoeo
eoeoeoe
oeoeoeo
eoeoeoe
oeoeoeo

我想将它们放入二维列表中,如下所示:

[['o', 'e', 'o', 'e', 'o', 'e', 'o'],
 ['e', 'o', 'e', 'o', 'e', 'o', 'e'],
 ['o', 'e', 'o', 'e', 'o', 'e', 'o'],
 ['e', 'o', 'e', 'o', 'e', 'o', 'e'],
 ['o', 'e', 'o', 'e', 'o', 'e', 'o']]

这就是我目前的做法:

map2dArray = []

for line in input_file:
    lineArray = []
    for character in line:
        lineArray.append(character)
    map2dArray.append(lineArray)

有没有更优雅的方式在 Python 中做到这一点?

【问题讨论】:

    标签: python arrays list loops


    【解决方案1】:

    是的,在一行中:

    map(list, input_file)
    

    或在 Python 3 中:

    list(map(list, input_file))
    

    这通常会在结果中留下换行符,所以如果你想摆脱那些:

    [list(line.strip('\n')) for line in input_file]
    

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多