Python 如何仅重复列表中的某个元素?
假设列表如下:Python 如何仅重复列表中的某个元素?,python,python-3.x,pandas,numpy,Python,Python 3.x,Pandas,Numpy,假设列表如下: article = ['a', 'b', 'c', 'd'] [['a', 'a'], 'b', 'c', 'd'] 和一个名为times的变量 现在,基于变量times的值,我只想重复文章列表中的元素'a' 例如: 如果时间=2 所需输出为 article = ['a', 'a', 'b', 'c', 'd'] article = ['a', 'a', 'a', 'b', 'c', 'd'] 同样,如果时间=3 所需输出为 article = ['a', 'a', 'b
article = ['a', 'b', 'c', 'd']
[['a', 'a'], 'b', 'c', 'd']
和一个名为times的变量
现在,基于变量times
的值,我只想重复文章
列表中的元素'a'
例如:
如果时间=2
所需输出为
article = ['a', 'a', 'b', 'c', 'd']
article = ['a', 'a', 'a', 'b', 'c', 'd']
同样,如果时间=3
所需输出为
article = ['a', 'a', 'b', 'c', 'd']
article = ['a', 'a', 'a', 'b', 'c', 'd']
我试着做:
[['a']*times, 'b', 'c', 'd']
但它给了我一个列表,如下所示:
article = ['a', 'b', 'c', 'd']
[['a', 'a'], 'b', 'c', 'd']
如何做到这一点?对加入列表使用
+
:
['a']*times + ['b', 'c', 'd']
在numpy中,可用于:
与您的方法类似,您可以使用以下内容创建内部列表:
times = 2
[*['a']*times, 'b', 'c', 'd']
# ['a', 'a', 'b', 'c', 'd']
您也可以为此使用切片和列表连接:
>>> article[:1] * 2 + article[1:]
['a', 'a', 'b', 'c', 'd']
[:1]
切片直到但不包括第一个索引<代码>[1::对所有内容进行切片,包括第一个索引 如果已经定义了文章
和时间
变量(或者它们来自您不想更改的函数),则可以使用这一函数。这还有一个优点,即要重复的元素可以位于任意索引中:
from typing import List, TypeVar
T = TypeVar('T')
def repeat_idx(ls: List[T], x: int, i: int) -> List[T]:
"""Return a new list with the element in the given index repeated x times.
Args:
ls: The list which element to repeat.
x: How many times to repeat the element.
i: The index of the element to repeat.
"""
return ls[:i] + [ls[i]]*x + ls[i + 1:]
article = ['a', 'b', 'c', 'd']
times = 3
print(repeat_idx(article, times, 0))
print(repeat_idx(article, times, 1))
print(repeat_idx(article, times, 3))
输出:
['a','a','b','c','d']
['a','b','b','b','c','d']
['a','b','c','d','d','d']
您可以在此处使用for循环:
times = 3
index = 2
l = ['a','b','c','d']
for i in range(times):
l.insert(index,l[index])
print(l)
“index”变量是要重复的元素的索引 列表中可以有几个
a
?“<代码> > <代码>是否在列表中间?