我想每隔一个元素向现有列表中插入一个元素。
假设列表是fruits = ["banana", "apple", "mango", "kiwi"],要添加元素"peach",我要做的是:
fruits = ["banana", "apple", "mango", "kiwi"]
fruits_2 = list(fruits)
for i in range(len(fruits)):
fruits_2.insert(2*i + 1, "peach")
print(fruits_2)
Run Code Online (Sandbox Code Playgroud)
输出是
['banana', 'peach', 'apple', 'peach', 'mango', 'peach', 'kiwi', 'peach']
Run Code Online (Sandbox Code Playgroud)
这就是我想要的,但是我感觉可能有一种更好且更简洁的方法,而无需创建第二个列表。
用zip,连同itertools.repeat和itertools.chain。
>>> from itertools import chain, repeat
>>> fruits = ["banana", "apple", "mango", "kiwi"]
>>> list(chain.from_iterable(zip(fruits, repeat("peach"))))
['banana', 'peach', 'apple', 'peach', 'mango', 'peach', 'kiwi', 'peach']
Run Code Online (Sandbox Code Playgroud)
repeat创建的无限序列'peach'。zip创建一系列对,由水果中的一个项目和一个实例组成'peach'。chain.from_iterable将对的序列“平化”为单个序列,并list从该序列中生成具体列表。
看中间步骤:
>>> from itertools import islice
>>> list(islice(repeat("peaches"), 5))
['peaches', 'peaches', 'peaches', 'peaches', 'peaches']
>>> zip(fruits, repeat("peaches"))
[('banana', 'peaches'), ('apple', 'peaches'), ('mango', 'peaches'), ('kiwi', 'peaches')]
Run Code Online (Sandbox Code Playgroud)
这种方法可以归结为一系列appends新清单,例如
result = []
for x in fruits:
result.append(x)
result.append("peaches")
Run Code Online (Sandbox Code Playgroud)
但是append,您无需对参数进行硬编码,而是从一对迭代器中获取它们:
def peach_source():
while True:
yield "peach"
def fruit_source(fruits):
for x in fruits:
yield x
result = []
peaches = peach_source()
fruits = fruit_source(fruits) # Yes, this is highly redundant; just showing the similarity to peach_source
done = False
while not done:
try:
result.append(next(fruits))
except StopIteration:
done = True
result.append(next(peaches))
Run Code Online (Sandbox Code Playgroud)
itertools.repeatpeach_source为您创造。zip处理获取水果和获取桃子之间的交替。chain.from_iterable定义附加到的操作result,并list实际执行附加操作。
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |