[英]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. 我想对每个内部值执行一个操作-例如串联,转换为
int
并递增等。
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
). 我宁愿使用数字列表(无需转换为
int
,返回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. 我们可以在这里使用eval函数。 About eval() What does Python's eval() do?
关于eval() Python的eval()做什么?
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(第一项)。 counters[0][0]
, for example, is the first item in the first sublist. 例如,
counters[0][0]
是第一子列表中的第一项。
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. eval
函数进行适当的转换,以便我们可以加1,而外部str
函数将最终答案转换回字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.