1

I've got a list like so:

counters = [["0"],["0"],["0"],["0"]]

I'd like to perform an operation to each of the inner values - say concatenation, converting to an int and incrementing, etc.

How can I do this for all of the list items; given that this is a multi-dimensional list?

Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55

4 Answers4

4

You can use list comprehension (nested list comprehension):

>>> counters = [["0"],["0"],["0"],["0"]]
>>> [[str(int(c)+1) for c in cs] for cs in counters]
[['1'], ['1'], ['1'], ['1']]

BTW, why do you use lists of strings?

I'd rather use a list of numbers (No need to convert to int, back to str).

>>> counters = [0, 0, 0, 0]
>>> [c+1 for c in counters]
[1, 1, 1, 1]
falsetru
  • 357,413
  • 63
  • 732
  • 636
1
  >>> counter=['0']*10
  >>> counter
   ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
  >>> counter=['1']*10
  >>> counter
  ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']
  overwrite a counter with 1,s
Benjamin
  • 2,257
  • 1
  • 15
  • 24
0
>>> counters = [["0"],["0"],["0"],["0"]]
>>> counters = [ [str(eval(i[0])+1)] for element in counters ]
>>> counters
[['1'], ['1'], ['1'], ['1']]

We can use eval function here. About eval() What does Python's eval() do?

Community
  • 1
  • 1
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
0

If list comprehension scares you, you can use sub-indexing. For example,

for i in range(len(counters)):
    counters[i][0] = str(eval(counters[i][0]) + 1)

counters is a list of lists, therefore you need to access the subindex of 0 (the first item) before you add to it. counters[0][0], for example, is the first item in the first sublist.

Moreover, each of your subitems is a string, not an integer or float. The eval function makes the proper conversion so that we can add 1, and the outer str function converts the final answer back to a string.

dcastello
  • 35
  • 8