列表转换 - 就地
List conversion - inplace
我正在尝试将 ['1','2','3','4'] 转换为 [1,2,3,4]
我想就地进行此转换。有可能做到吗?如果不是,最优解是什么
这应该差不多就位了吧?
In [31]: l = ['1','2','3','4']
In [32]: for i in range(len(l)):
....: l[i] = int(l[i])
....:
In [33]: l
Out[33]: [1, 2, 3, 4]
或者,您可以使用 enumerate
来实现,它接受一个可迭代对象(如 list
)和 returns 一个 index
以及从头开始的相应值直到最后:
In [84]: l = ['1','2','3','4']
In [85]: for idx, val in enumerate(l):
....: l[idx] = int(val)
....:
In [86]: l
Out[86]: [1, 2, 3, 4]
只要整个数组适合内存,您就应该能够单步执行它,边走边替换每一项:
# bigarray is ['1','2','3','4',...];
# loop through bigarray using index i
for i in range(len(bigarray)):
# coerce bigarray[i] to int in place
bigarray[i] = int(bigarray[i])
# bigarray is [1,2,3,4,...];
祝你好运!
你可以像这样用列表理解来做到这一点:
l = [int(item) for item in l]
我认为这种任务最好使用 map
。它创建迭代器,这意味着它的内存效率更高。
l = list(map(int, l))
# here I convert it to list, but usually you would just iterate over it
# so you can just do
for item in map(int, l):
...
我正在尝试将 ['1','2','3','4'] 转换为 [1,2,3,4] 我想就地进行此转换。有可能做到吗?如果不是,最优解是什么
这应该差不多就位了吧?
In [31]: l = ['1','2','3','4']
In [32]: for i in range(len(l)):
....: l[i] = int(l[i])
....:
In [33]: l
Out[33]: [1, 2, 3, 4]
或者,您可以使用 enumerate
来实现,它接受一个可迭代对象(如 list
)和 returns 一个 index
以及从头开始的相应值直到最后:
In [84]: l = ['1','2','3','4']
In [85]: for idx, val in enumerate(l):
....: l[idx] = int(val)
....:
In [86]: l
Out[86]: [1, 2, 3, 4]
只要整个数组适合内存,您就应该能够单步执行它,边走边替换每一项:
# bigarray is ['1','2','3','4',...];
# loop through bigarray using index i
for i in range(len(bigarray)):
# coerce bigarray[i] to int in place
bigarray[i] = int(bigarray[i])
# bigarray is [1,2,3,4,...];
祝你好运!
你可以像这样用列表理解来做到这一点:
l = [int(item) for item in l]
我认为这种任务最好使用 map
。它创建迭代器,这意味着它的内存效率更高。
l = list(map(int, l))
# here I convert it to list, but usually you would just iterate over it
# so you can just do
for item in map(int, l):
...