Python列表(list)所有元素的同一操作

针对很普遍的每个元素的操作会遍历每个元素进行操作。

这里给出了几种写法,列表每个元素自增等数学操作同理

 

示例:整形列表ilist加1个数、元素类型转字符串:

 1 ilist = [1, 2, 3, 10, 11, 12]
 2 
 3 
 4 # 每个元素加5,四种方法
 5 for i, v in enumerate(ilist): ilist[i] = v + 5
 6 [ x+5 for x in ilist ]
 7 map(lambda x:x+5, ilist) # 仅python 2
 8 list(map(lambda x:x+5, ilist))
 9 [*map(lambda x:x+5, ilist)] # 仅python 3
10 
11 
12 # 整形元素转字符串,两种方法
13 list(map(str, ilist)) 
14 [*map(str, ilist)] # 仅python 3

执行结果如下图:

 

参考:
https://www.geeksforgeeks.org/python-convert-a-list-of-multiple-integers-into-a-single-integer/
https://stackoverflow.com/questions/3371269/call-int-function-on-every-list-element

posted @ 2019-07-31 21:15  oucbl  阅读(19975)  评论(1编辑  收藏  举报