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

2024-06-26 18:10:13 发布

您现在位置: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')

我想完全删除/删除第一个列表['', '', '', ''],但我很难做到这一点。你知道吗


Tags: 文件数据lambda标题map列表linefilename
2条回答

只需使用内置函数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

试试这个

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

remove列表包含与要删除的列表完全相同的列表,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']]

干杯

相关问题 更多 >