简体   繁体   English

替换列表中的所有其他 position

[英]Replacing every other position in a list

I'm trying to make something that allows me to replace every other position in a list with a single item:我正在尝试制作一些东西,使我可以用单个项目替换列表中的所有其他 position:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l[::2] = "A"
print(l)

I'm expecting something like:我期待类似的东西:

["A", 1, "A," 3, "A", "A", 6, "A", 8, "A", 10]

I've tried different positions of indexing [::] but either get an error or a result that doesn't include the rest of the list.我尝试了索引[::]的不同位置,但要么得到错误,要么得到不包括列表中 rest 的结果。

Instead I get this:相反,我得到了这个:

ValueError: attempt to assign sequence of size 1 to extended slice of size 2

The slice is correct, but you need to provide a sequence with enough elements to fill all the elements.切片是正确的,但您需要提供一个包含足够元素的序列来填充所有元素。

l[::2] = ["A"] * math.ceil(len(l)/)

Edit: Barmar's answer is much better, so long as you're okay importing the math library.编辑:Barmar 的答案要好得多,只要您可以导入数学库。

Rough speed comparison at 10,000 loops (assuming you don't turn the list into a generator, otherwise the list comprehension becomes slightly faster overall): 10,000 个循环的粗略速度比较(假设您没有将列表变成生成器,否则列表理解总体上会稍微快一些):

import math, time

def slicing(n):
    for _ in range(n):
        l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        l[::2] = ["A"] * math.ceil(len(l)/2)

def comprehension(n):
    for _ in range(n):
        l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        l = ["A" if i % 2 == 0 else elem for i, elem in enumerate(l)]

start = time.time()
slicing(10000)
print(f'Using slicing and math.ceil: {time.time() - start} seconds')

start = time.time()
comprehension(10000)
print(f'Using list comprehension:    {time.time() - start} seconds')

>>> Using slicing and math.ceil: 0.004003286361694336 seconds
>>> Using list comprehension:    0.012019157409667969 seconds

Old answer:老答案:

Try using a list comprehension paired with enumerate :尝试使用与enumerate配对的列表理解:

l = ["A" if i % 2 == 0 else elem for i, elem in enumerate(l)]

This replaces every element with an odd index (odd numbers % 2 will equal 0) with the letter "A", and leaves the remaining elements as they are.这将用字母“A”的奇数索引(奇数 % 2 将等于 0)替换每个元素,并将其余元素保持原样。 Enumerate loops over the original iterable, but includes an index element as well. Enumerate 循环遍历原始的可迭代对象,但也包含一个索引元素。

You must provide as many elements as there are items to assign:您必须提供与要分配的项目一样多的元素:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

l[::2] = ("A" for _ in l[::2])

print(l)
['A', 1, 'A', 3, 'A', 5, 'A', 7, 'A', 9, 'A']

Or this way:或者这样:

l[::2] = ["A"]*len(range(0,len(l),2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM