Python:从列表中删除项目

时间:2015-11-09 03:53:57

标签: python list

我的数据如下:

hashtags = [['mobile', 'data', 'cx', 'rt'],
            ['drivers', 'data', 'analytics'],
            ['data'],
            ['data', 'math']]

我想从上面的列表中删除'data',因此预期的输出将是:

hashtags = [['mobile', 'cx', 'rt'],
            ['drivers', 'analytics'],
            ['math']]

我试过了:

for item in hashtags:
    print item.remove('data')

但是,代码返回:

None
None
None
None

有什么建议吗?

4 个答案:

答案 0 :(得分:4)

使用list comprehension

>>> hashtags = [['mobile', 'data', 'cx', 'rt'],
            ['drivers', 'data', 'analytics'],
            ['data'],
            ['data', 'math']]
>>> [[j for j in i if j != 'data'] for i in hashtags]
[['mobile', 'cx', 'rt'], ['drivers', 'analytics'], [], ['math']]
>>> [k for k in [[j for j in i if j != 'data'] for i in hashtags] if len(k) > 0 ]
[['mobile', 'cx', 'rt'], ['drivers', 'analytics'], ['math']]

为了更好的可读性,

>>> [lst for lst in [[itm for itm in sublst if itm != 'data'] for sublst in hashtags] if len(lst) > 0 ]
[['mobile', 'cx', 'rt'], ['drivers', 'analytics'], ['math']]
>>> 

答案 1 :(得分:1)

你可以得到这样的结果:

for list in hashtags:
    list.remove('data')
    if list == []:
        hashtags.remove(list)

答案 2 :(得分:0)

函数item.remove( ... )不返回值,它只是从列表中删除所述值。你应该这样做:

hashtags.remove(["data"])

然后像这样打印列表:

print hashtags

答案 3 :(得分:-3)

for sublist in hashtags:
    sublist.remove('data')