PerczynskiAdam
PerczynskiAdam

Reputation: 87

Function appending true or false not work correctly

I make a list:

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']]

I want to find where are empty list and iterate over them to get information about every person and store it as dataframe. For example:

Row 1: John Football Liverpool Salah Striker

Row 2: James F1 Ferrari Raikkonen Driver

Column: John James etc

To do so i tried function which save to list True when length of list is 0 and False otherwise.

Then i use itertools.compress to print items which selectors are 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)

The problem is that selectors have more elements then i expected (14 instead of 12). Between True and next True i have 4 times False but should be 3 times and one additional False after second True.

Why is that and how to fixed it? Is there any faster/better way to solve whole problem?

Upvotes: 1

Views: 44

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

Problem is the missing else: - see hiro's answer - it always appends the False .


Zen of python: #3 - Simple is better than complex.

You do not need itertools.compress at all:

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

is the same as:

zip_nest_list = list(enumerate(nest_list))

To get the indexes of the empty list you can use a list comprehension:

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

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

Output:

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

Doku:

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46911

you forgot the else clause in your if statement; False is appended to selectors in any case. it should be:

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

Upvotes: 2

Related Questions