转置列表列表-空输出,python

时间:2019-10-01 04:23:34

标签: python list

我正在尝试转置我创建的列表列表。我通过将列表彼此追加来制成列表列表:我有四个列表,每个列表包含十个项目。

这是我的列表列表。 [['Bin1', 'Bin2', 'Bin3', 'Bin4', 'Bin5', 'Bin6', 'Bin7', 'Bin8', 'Bin9', 'Bin10'], ['TTF is greater than or equal to 50.0,', 'TTF is greater than or equal to 88.0,', 'TTF is greater than or equal to 126.0,', 'TTF is greater than or equal to 164.0,', 'TTF is greater than or equal to 202.0,', 'TTF is greater than or equal to 240.0,', 'TTF is greater than or equal to 278.0,', 'TTF is greater than or equal to 316.0,', 'TTF is greater than or equal to 354.0,'], ['less than 88.0:', 'less than 126.0:', 'less than 164.0:', 'less than 202.0:', 'less than 240.0:', 'less than 278.0:', 'less than 316.0:', 'less than 354.0:', 'less than or equal to 430.0:'], [17, 29, 25, 9, 8, 3, 4, 1, 2, 2]]

我使用此代码尝试对列表列表进行转置,但是它不起作用。

def transpose(lst):
    newlist = []
    i = 0
    while i < len(lst):
        j = 0
        colvec = []
        while j < len(lst):
            colvec.append(lst[j][i])
            j = j + 1
        newlist.append(colvec)
        i = i + 1
    return newlist

此代码仅返回一对空括号[]。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

简单的解决方案:

def transpose(a):
  r = len(a)
  c = len(a[0])
  print(r,c)
  b = []
  for i in range(c):
    b.append([0]*r)
  for i in range(r):
    for j in range(c):
      b[j][i] = a[i][j]
  print(b)

我建议使用numpy.ndarray.T

import numpy as np    
a = np.array([[5, 4],[1, 2]])
print(a)
print(a.T)

输出:

[[5 4]
 [1 2]]
[[5 1]
 [4 2]]