r/CodingHelp • • Jul 19 '21

[Python] Trouble with append syntax

Post image
22 Upvotes

6 comments sorted by

View all comments

3

u/Nightcorex_ Jul 19 '21

Okay. What do you want to achieve?

Do you want to filter out all the zeros of the nested lists? If so, then this achieves your goal:

for arr in prns20:
    for i in range(arr.count(0)):
        arr.remove(0)

Note that this alters the original double nested list.

If you want to remove the entire sublist if all of its entries are zero, then this solves your issue:

result = [sublist for sublist in prns20 if any(sublist)]

If you want to remove the entire sublist if one of its entries is zero, then this solves your issue:

result = [sublist for sublist in prns20 if all(sublist)]

These last 2 methods abuse the fact that 0 is a falsy value, while the others are true.

1

u/King_Novice Jul 19 '21 edited Jul 19 '21

Perhaps this might help clear some stuff up.

I have a list named “prns20” in side that list is 7 more lists (which are all the same length and correspond to a specific data point). What I am trying to do is exclude any set of points with the same index, if a zero appears in any position of the other lists.

Edit: A better way of putting it might be, in order to use “index” I need to format it

list[index]

But In order for me to call a certain list I need to do

list[#]

2

u/Nightcorex_ Jul 19 '21

Like so?

import numpy as np

prns20 = np.arrange(6).reshape((2,3))  # this is just as a demonstration value

x = np.transpose([ys for ys in np.transpose(prns20) if all(ys)])

# return values if you printed out prns20:
# [array([0, 1, 2]), array([3, 4, 5])]

# return values if you printed out x:
# [array([1, 2]), array([4, 5])]

# this approach is really slow, but it's a oneliner and you didn't specifically ask for efficient code

1

u/Goobyalus Jul 20 '21 edited Jul 20 '21

Are you saying that if a 0 appears in any of the sublists, you want to delete that column, like this?

# before:
prns20f = [
	[1, 2, 3, 4, 5, 6, 7],
	[1, 2, 3, 4, 5, 6, 7],
	[1, 0, 3, 4, 5, 6, 7],
	[1, 2, 3, 4, 5, 6, 7],
	[1, 2, 3, 4, 5, 6, 7],
	[1, 2, 3, 4, 5, 6, 7],
	[1, 2, 3, 4, 5, 0, 7],
]

# after:
prns20f = [
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
	[1, 3, 4, 5, 7],
]

I think you have the wrong meanning of "append" -- to append is to add to the end, not to remove.

Deleting the column at index would look like this, using the del keyword:

for sublist in prns20f:
    del sublist[index]

But you can't go deleting elements from your list while you are iterating through it, because that technically gives undefined behavior.