0

大家好,我在从大量 1d 列表中创建 2d 列表时遇到问题。我的代码如下

  lis=[average, average1, average2, average3, average4, average5, average6, average7, average8, average9]
  totalaverage= 3


  print
  print "Station 1 = Station 0 from menu. Please read all other stations accordingly"
  print
  for i,x in enumerate(lis):
  if x < totalaverage:
    aboveaverage = " {} average is less than {}".format(i+1,totalaverage )


    option = 0
    comicdb = []

    record = {}
    record = aboveaverage
    comicdb.append(record)
    print comicdb


    elif x > totalaverage:
     belowaverage = "{} average is greater than {}".format(i+1,totalaverage)
     print belowaverage

当我打印 Comicdb 时,我得到以下结果。

[' 1 average is less than 3']
[' 2 average is less than 3']
[' 3 average is less than 3']
[' 4 average is less than 3']
[' 5 average is less than 3']
[' 6 average is less than 3']
[' 7 average is less than 3']
[' 8 average is less than 3']
[' 9 average is less than 3']
[' 10 average is less than 3']

我想知道的是。有没有可以添加的代码,所以我可以将所有这些单列表组合成一个双列表,这样我的代码在打印时看起来像这样。

[[' 1 average is less than 3'],
[' 2 average is less than 3'],
[' 3 average is less than 3'],
[' 4 average is less than 3'],
[' 5 average is less than 3'],
[' 6 average is less than 3'],
[' 7 average is less than 3'],
[' 8 average is less than 3'],
[' 9 average is less than 3'],
[' 10 average is less than 3']]

本质上,我希望将所有这些单独的列表组合成一个双重列表,以便我可以使用双重列表单独访问每个列表。我想稍后在代码中单独打印每个列表。

4

1 回答 1

1

在 python 中,您可以将列表附加到列表中。

new_list = []
for i,x in enumerate(lis):
if x < totalaverage:
    aboveaverage = " {} average is less than {}".format(i+1,totalaverage )
    option = 0
    comicdb = []
    record = {}
    record = aboveaverage
    comicdb.append(record)
    new_list.append(comicdb)
    print comicdb

    elif x > totalaverage:
        belowaverage = "{} average is greater than {}".format(i+1,totalaverage)
        print belowaverage
print new_list
于 2013-05-29T06:55:37.523 回答