python - 如何只重复列表中的某个元素?

标签 python python-3.x pandas numpy

假设列表如下:

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.repeatnumpy.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/

相关文章:

python - 从多个文件构造数据框,其中每个文件包含列数据

python - Keras 使用 LSTM 进行情感分析如何测试

python - Pandas datetime64 到字符串

Python:根据多个分组对唯一变量进行分组和计数而无需重新计数

python - fancyimpute Python 3 内存错误

c++ - 关于 Boost::Python 和 Boost::Threads 的问题

python - pyspark RDD countByKey() 是如何计数的?

python - 如何避免属性错误: 'NoneType' object has no attribute 'text' webscraping subreddits?

python - 如何修改此代码以用于多个列表?

python - matplotlib/ Pandas : put line label along the plotted lines in time series plot