list iteration if statement

A

alex goretoy

Hello All,

I'm doing this in my code

[[v.append(j) for j in i] for i in self.value]

if works and all, but I need to add a if statement in the mix. Can't seem to
remember the syntax to do so and everything I've tried seems to fail. How do
I add a check to see if j is not int("0") then append to v list? Thank you
in advance. -A
 
S

Steven D'Aprano

Hello All,

I'm doing this in my code

[[v.append(j) for j in i] for i in self.value]

if works and all,

Replacing "self.value" with a list of lists of ints:
list_of_lists = [[1, 2, 3], [2, 4, 6]]
v = []
output = [[v.append(j) for j in sublist] for sublist in list_of_lists]
v [1, 2, 3, 2, 4, 6]
output
[[None, None, None], [None, None, None]]


So you create two lists, one is a copy of self.value which has been
flattened, and the other is a nested list of nothing but None. What a
waste of effort if your input is large.

Why not just do the obvious for loop?

v = []
for L in list_of_lists:
for item in L:
v.append(item)

but I need to add a if statement in the mix.

Using a for loop, it should be obvious:

v = []
for L in list_of_lists:
for item in L:
if item != 0: v.append(item)

Can't
seem to remember the syntax to do so and everything I've tried seems to
fail.

If you *insist* on doing it the wrong way,


[[v.append(j) for j in i if j != 0] for i in self.value]

How do I add a check to see if j is not int("0") then append to v
list? Thank you in advance. -A

Is there some significance of you saying int("0") instead of 0?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top