从列表中的列表中删除空值

时间:2015-11-16 08:57:38

标签: python regex list

我需要有关如何从列表中的列表中删除null,空字符串的帮助。

res = [ ['', 'ACTION', 'ADVENTURE', 'FANTASY', ''],
 ['', 'ACTION', 'DRAMA', 'ROMANCE', ''],
 ['', 'HISTORY', 'ROMANCE', 'WAR', ''],
 ['', 'DRAMA', 'THRILLER', ''],
 ['', 'DRAMA', 'THRILLER', ''],
 ['', 'COMEDY', 'DRAMA', 'ROMANCE', ''],
 ['', 'ADVENTURE', 'COMEDY', ''],
 ['', 'ACTION', 'THRILLER', '']]

如果它像是

res = ['', 'ACTION', 'ADVENTURE', 'FANTASY', '']

我愿意

res = [x for x in res if x ]

但是如何从列表中删除列表。 请建议。

我还需要从该列表中找到每个项目计数,例如。行动计数,THRILLER计数。

3 个答案:

答案 0 :(得分:4)

试试这个

res1 = [[i for i in j if i] for j in res]
dictt = {}
[[dictt.__setitem__(i, dictt.setdefault(i, 0) + 1) for i in j] for j in res1]

答案 1 :(得分:3)

映射并过滤res列表:

map(lambda x:filter(lambda y: y != "", x), res)


>>> map(lambda x:filter(lambda y: y != "", x), res)
[['ACTION', 'ADVENTURE', 'FANTASY'], ['ACTION', 'DRAMA', 'ROMANCE'], ['HISTORY', 'ROMANCE', 'WAR'], ['DRAMA', 'THRILLER'], ['DRAMA', 'THRILLER'], ['COMEDY', 'DRAMA', 'ROMANCE'], ['ADVENTURE', 'COMEDY'], ['ACTION', 'THRILLER']]

计算:

import collections
c = Counter(reduce(lambda x, y: x+y, filtered_res))

>>> filtered_res= map(lambda x:filter(lambda y: y != "", x), res)
>>> c = Counter(reduce(lambda x, y: x+y, filtered_res))
>>> c["DRAMA"]
4

答案 2 :(得分:1)

使用' old-fashioned` for循环,您可以删除空条目并按类别获取总计数:

res = [ ['', 'ACTION', 'ADVENTURE', 'FANTASY', ''],
 ['', 'ACTION', 'DRAMA', 'ROMANCE', ''],
 ['', 'HISTORY', 'ROMANCE', 'WAR', ''],
 ['', 'DRAMA', 'THRILLER', ''],
 ['', 'DRAMA', 'THRILLER', ''],
 ['', 'COMEDY', 'DRAMA', 'ROMANCE', ''],
 ['', 'ADVENTURE', 'COMEDY', ''],
 ['', 'ACTION', 'THRILLER', '']]

counts = {}
cleaned = []
for categories in res:        
    cleaned.append([]);
    for category in categories:        
        if category !='':           
            cleaned[-1].append(category) 
            if category in counts:
                counts[category]= counts[category] +1
            else:
                counts[category]=1;            

print counts['ACTION']