假设列表如下:
article = ['a', 'b', 'c', 'd']
和一个名为 times
的变量
现在,基于变量 times
的值,我只想重复元素 'a'
在 article
列出很多次。
例如:
如果times = 2
,
所需输出为
article = ['a', 'a', 'b', 'c', 'd']
类似地,如果 times = 3
,
所需输出为
article = ['a', 'a', 'a', 'b', 'c', 'd']
我尝试这样做:
[['a']*times, 'b', 'c', 'd']
但它给了我一个列表中的列表,如下所示:
[['a', 'a'], 'b', 'c', 'd']
如何做到这一点?
最佳答案
使用+
加入列表:
['a']*times + ['b', 'c', 'd']
在 numpy 中可以使用 numpy.repeat
与 numpy.concatenate
:
article = ['a', 'b', 'c', 'd']
times = 3
b = np.concatenate([np.repeat(['a'], times), ['b', 'c', 'd']]).tolist()
print(b)
['a', 'a', 'a', 'b', 'c', 'd']
关于python - 如何只重复列表中的某个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704268/