简体   繁体   中英

How to perform an operation on all values of a 2D list in Python

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM