如何向列表中的每个元素添加一个整数?
- 2025-02-27 09:06:00
- admin 原创
- 86
问题描述:
如果我有list=[1,2,3]
,并且想添加1
到每个元素以获取输出[2,3,4]
,我该怎么做?
我假设我会使用 for 循环但不确定具体如何使用。
解决方案 1:
new_list = [x+1 for x in my_list]
解决方案 2:
关于列表理解的其他答案可能是简单加法的最佳选择,但如果您有一个需要应用于所有元素的更复杂的函数,那么map可能是一个不错的选择。
在您的示例中它将是:
>>> map(lambda x:x+1, [1,2,3])
[2,3,4]
解决方案 3:
>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>
列表推导式 python。
解决方案 4:
如果你想使用 numpy,还有另一种方法如下
import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)
解决方案 5:
编辑:这还未到位
首先,不要对变量使用单词 'list'。它会遮盖关键字list
。
最好的方法是使用拼接来现场完成,注意[:]
表示拼接:
>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]
解决方案 6:
>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]
我的目的是揭示列表中的项目是否是整数,它是否支持各种内置函数。
解决方案 7:
Python 2+:
>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]
Python 3+:
>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]
解决方案 8:
import numpy as np
np.add([1, 2, 3], 1).tolist()
由此得出
[2, 3, 4]
解决方案 9:
以防万一有人正在寻找仅使用内置而不使用lambda
s 的解决方案:
from functools import partial
from operator import add
my_list = range(1, 4) # list(my_list) #=> [1, 2, 3]
my_list_plus_one = list(map(partial(add, 1), my_list) #=> [2, 3, 4]
解决方案 10:
发现了一种不太有效但又独特的方法。所以分享它。而且它需要额外的空间来容纳另一个列表。
from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)
res_list = list(map(add, test_list1, test_list2))
print(test_list1)
print(test_list2)
print(res_list)
#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]
解决方案 11:
list = [1,2,3,4,5]
for index in range(len(list)):
list[index] = list[index] +1
print(list)
解决方案 12:
上面的许多答案都很好。我也看到过一些可以完成工作的奇怪答案。此外,看到的最后一个答案是通过正常循环。这种给出答案的意愿让我想到了itertools
和numpy
,它们将以不同的方式完成相同的工作。
在这里,我介绍了完成这项工作的不同方法,上面没有回答。
import operator
import itertools
x = [3, 5, 6, 7]
integer = 89
"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
print(i, end = ",")
# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)
# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy
res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape
# if you specifically want a list, then use tolist
res_list = res.tolist()
print(res_list)
输出
>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96, # output of iterating above starmap object
>>> [92, 94, 95, 96] # output obtained by casting to list
>>> __
>>> # | | | | |/| |__| /
>>> # | | |__| | | | |
>>> [92 94 95 96] # this is numpy.ndarray object
>>> (4,) # shape of array
>>> [92, 94, 95, 96] # this is a list object (doesn't have a shape)
我强调使用它的唯一numpy
原因是,人们应该始终使用像 numpy 这样的库进行此类操作,因为它对于非常大的数组来说性能效率很高。
解决方案 13:
有很多好的解决方案,这里有一些基准测试。
from functools import partial
from operator import add
test_list = list(range(1000)); n = 3;
%timeit _=list(map(lambda x:x+n, test_list))
%timeit _=[x+n for x in test_list]
%timeit _=[x.__add__(n) for x in test_list]
%timeit _=list(map(lambda x:x.__add__(n), test_list))
%timeit _=list(map(partial(add,n), test_list))
Out:
>> 53.6 µs ± 651 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
>> 38.2 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
>> 80.2 µs ± 851 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
>> 108 µs ± 513 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
>> 53.7 µs ± 332 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
似乎[x+n for x in test_list]
是纯 Python 中最快的解决方案。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD