Starter
Starter

Reputation: 417

Increment values in a list of lists starting from 1

I have a list of lists e.g [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1]]

My desired output is [[0, 0], [1, 0], [2, 0], [3, 4], [0, 5]]

That is, I wish to modify the list such that if the value is not zero, I set it to the count, which starts at 1 and increments by 1 for each non-zero value. If it's 0, I keep it as 0.

How do I go about this? I started by indexing using enumerate but it's harder than I thought.

Here is what I have done: w generates the initial list. This is not my full code because it is too long to post.

w = [[i if i != l else 0 for i in x] for x in c]
print(w)
inc = 1
lx = []
gg = []
for i in w:
   if i[0] or i[1] !=0:
      g = w.index(i)
      gg.append(g)
      lx.append(i)
for x in gg:
   for i, v in enumerate(w):
       if x==i:
          if
          print(x, i, v)

Thank you

Upvotes: 0

Views: 750

Answers (3)

Austin
Austin

Reputation: 26057

This would also work, probably more pythonic and shorter, using a list-comprehension:

from itertools import count

lst = [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1]]
counter = count(1)

lst = [[next(counter) if x != 0 else 0 for x in sublst] for sublst in lst]
# [[0, 0], [1, 0], [2, 0], [3, 4], [0, 5]]

Learn more about how itertools.count works here, meanwhile here is a small snippet for a better understanding:

>>> import itertools
>>> c = itertools.count(1)
>>> next(c)
1
>>> next(c)
2

Upvotes: 3

Serge
Serge

Reputation: 3775

If your sublists are two element you can get rid of enumerate

from itertools import count
counter = count(1)
lst = [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1]]
for pair in lst:
    pair[0] = next(counter) if pair[0] else 0
    pair[1] = next(counter) if pair[1] else 0
print(lst)

For longer or variable sublists you may use either enumerate, map or list comprehension

from itertools import count
counter = count(1)
lst = [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1], [0, 1, 3, 3, 3], [3]]
for sublist in lst:
    sublist[:] = map(lambda x: (next(counter) if x else 0), sublist)
    # slice assignment is 'in-place' assignment



from itertools import count
counter = count(1)
lst = [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1], [0, 1, 3, 3, 3], [3]]
for sublist in lst:
    for i, element in enumerate(sublist):
        sublist[i] = next(counter) if element else 0 

Upvotes: 0

pushkin
pushkin

Reputation: 10247

I think you're over-complicating this. If either elem is 0, you don't need to touch it. If it's something else, increment the count and stick it in the right place.

nums = [[0, 0], [4, 0], [2, 0], [5, 3], [0, 1]]
count = 0
for i,(a,b) in enumerate(nums):
  if a != 0:
    count += 1
    nums[i][0] = count
  if b != 0:
    count += 1
    nums[i][1] = count

print nums

Output:

[[0, 0], [1, 0], [2, 0], [3, 4], [0, 5]]

Upvotes: 1

Related Questions