附加true或false的函数无法正常工作

时间:2019-02-10 09:57:40

标签: python python-3.x itertools

我列出一个列表:

nest_list = [['John like to play football'],['He likes Liverpool'],
             ['His favourite player is Salah'],['He would like to play as striker'],
             [],['James like to play F1'],['He likes Ferrari'],
             ['His favourite driver is Raikkonnen'],[],
             ['Stefani like to play basketball'],['She likes Chicago Bulls'],
             ['His favourite player is Micheal Jordan']]

我想找到空列表,然后遍历它们以获取有关每个人的信息并将其存储为数据框。例如:

Row 1: John Football Liverpool Salah Striker

Row 2: James F1 Ferrari Raikkonen Driver

Column: John James etc

为此,我尝试了当列表的长度为0时保存到列表True的函数,否则为False

然后我使用itertools.compress打印选择器为True的项目。

zip_nest_list = list(zip(range(len(nest_list)),nest_list))
import itertools

selectors = []
def is_empty(i):
    '''Create selectors list with True when empty list and false when not empty'''
    if len(zip_nest_list[i][1]) == 0:
        selectors.append(True)
    selectors.append(False)

for x in range(len(zip_nest_list)):
    is_empty(x)


result = itertools.compress(zip_nest_list,selectors)
#printing empty lists with number
for item in result:
    print(item)

问题是选择器比我期望的要多(14个而不是12个)。在True和下一个True之间,我有4倍False,但应该是3倍,并且在第二False之后又有一个True

为什么会这样以及如何解决?有什么更快/更好的方法来解决整个问题?

2 个答案:

答案 0 :(得分:2)

您忘记了else语句中的if子句;在任何情况下,False都会附加到selectors之后。应该是:

if len(zip_nest_list[i][1]) == 0:
    selectors.append(True)
else:
    selectors.append(False)

答案 1 :(得分:1)

问题是缺少的else:-请参见hiro's answer-它总是附加False


Zen of python: #3-简单胜于复杂。

您根本不需要itertools.compress

zip_nest_list = list(zip(range(len(nest_list)),nest_list))

与以下相同:

zip_nest_list = list(enumerate(nest_list))

要获取空列表的索引,可以使用list comprehension

empties = [ x for x in enumerate(nest_list) if not x[1]] # empty list is Falsy

print( *empties, sep="\n")

输出:

(4, [])
(8, [])

Doku: