Python:从一系列列表中删除列表

时间:2016-01-05 10:10:38

标签: python

我有一系列列表是从导入的文件中创建的,其中包含大量数据。但是,从文件创建列表时,还会为标题创建列表。我已设法从第一个列表中删除标题,但现在已经留下了:

['', '', '', '']
['2.3', '82.2', '0.6', '1.5']
['3.6', '92.9', '0.5', '2.1']
['6.3', '82.9', '0.7', '2.1']
['7.0', '70.8', '0.5', '1.8']
['7.7', '56.3', '0.4', '2.0']
['8.3', '97.0', '0.8', '1.8']
['10.4', '67.0', '0.6', '1.5']
['11.8', '89.3', '0.7', '1.4']
['13.0', '75.8', '0.8', '1.3']
['14.1', '77.1', '0.6', '1.7']
['15.8', '74.6', '0.6', '1.8']
['16.9', '69.0', '0.4', '2.5']
['18.4', '89.9', '0.6', '2.4']
['20.3', '93.5', '0.9', '2.3']
['21.4', '80.9', '0.6', '1.9']
['21.9', '81.6', '0.9', '2.2']
['23.5', '65.0', '0.6', '2.5']
['24.4', '78.4', '0.4', '1.8']
['27.2', '81.5', '0.7', '2.3']
['28.8', '73.4', '0.4', '1.7']

代码:

def createPersonList(fileName):
    theFile = open(fileName)
    for line in theFile:
        aList = line.split(',')
        bList = map(lambda s: s.strip('\n'), aList)
        cList = map(lambda s: s.strip('ArrivalTime (s)'' Weight (kg)'' gait (m)' ' speed (m/s)'), bList)
        print cList

输入:

>>>createPersonList('filename')

我想完全删除/删除第一个列表['', '', '', ''],但我很难这样做。

2 个答案:

答案 0 :(得分:1)

您可以使用内置函数next()跳过第一行:

def createPersonList(fileName):
    theFile = open(fileName)
    next(theFile) # skips the first line
    for line in theFile: # goes through the rest of the lines in the file

答案 1 :(得分:0)

试试这个

remove = ['', '', '']
print [data for data in s if all(x not in remove for x in data)]

删除列表包含与要删除的内容完全相同的列表,s是包含所有子列表的完整列表

仅供参考s

s=[['', '', '', ''],
['2.3', '82.2', '0.6', '1.5'],
['3.6', '92.9', '0.5', '2.1'],
['6.3', '82.9', '0.7', '2.1'],
['7.0', '70.8', '0.5', '1.8'],
['7.7', '56.3', '0.4', '2.0'],
['8.3', '97.0', '0.8', '1.8'],
['10.4', '67.0', '0.6', '1.5'],
['11.8', '89.3', '0.7', '1.4'],
['13.0', '75.8', '0.8', '1.3'],
['14.1', '77.1', '0.6', '1.7'],
['15.8', '74.6', '0.6', '1.8'],
['16.9', '69.0', '0.4', '2.5'],
['18.4', '89.9', '0.6', '2.4'],
['20.3', '93.5', '0.9', '2.3'],
['21.4', '80.9', '0.6', '1.9'],
['21.9', '81.6', '0.9', '2.2'],
['23.5', '65.0', '0.6', '2.5'],
['24.4', '78.4', '0.4', '1.8'],
['27.2', '81.5', '0.7', '2.3'],
['28.8', '73.4', '0.4', '1.7']]

干杯