在Python中的列表中插入元素

问题描述 投票:0回答:4

我有一个清单

x0
。我想根据
missing_values
的元素插入索引。我介绍当前和预期的输出。

x0 = [1, 2, 3, 4, 5]
missing_values = [2, 4]  # indices to set to zero

# Create a set of indices from missing_values
indices_to_set_zero = set(missing_values)

# Initialize the result list
result = []

# Iterate through x0
for i, value in enumerate(x0):
    # If the index is in the set, append 0 before the value
    if i in indices_to_set_zero:
        result.append(0)
    result.append(value)

# If the last index is in the set, append a 0 at the end
if len(x0) in indices_to_set_zero:
    result.append(0)

print(result)

当前输出为

[1, 2, 0, 3, 4, 0, 5]

预期输出是

[1, 0, 2, 0, 3, 4, 5]
python list
4个回答
0
投票

首先,你没有考虑到索引是从 0 而不是 1 开始的。


0
投票

您不能依赖枚举进行索引,因为插入每个 0 都会在索引中进一步移动新列表的所有其他元素。您需要检查新创建的列表的下一个元素是否与应包含 0 的索引匹配 - 如果是,则追加 0,否则追加原始列表中的下一个元素:

x0 = [1, 2, 3, 4, 5]
missing_values = [2, 4]  # indices to set to zero

it = iter(missing_values)
next_miss = next(it)

out = []

for el in x0:
    try:
        if next_miss is not None and len(out) == next_miss - 1:
            out.append(0)
            next_miss = next(it)
    except StopIteration:
        next_miss = None
    out.append(el)

print(out) # [1, 0, 2, 0, 3, 4, 5]

0
投票

由于列表是从 0 开始索引的 你需要减去 1,这样它就会以索引 1 和 3 结束

x0 = [1, 2, 3, 4, 5]
missing_values = [2, 4]


result = x0[:]


for i, position in enumerate(missing_values):
    # Convert 1-based position to 0-based index and adjust for previous insertions
    index_to_insert = position - 1
    # Insert zero at the calculated index
    result.insert(index_to_insert, 0)

print(result)

0
投票

正如@user24803130所说,Python列表是零索引的。如果您希望索引从 1 开始,则必须扣除该值。 您可以使用列表的

insert
功能:

x0 = [1, 2, 3, 4, 5]
missing_values = [2, 4]  # indices to set to zero

for i in missing_values:
    x0.insert(i-1, 0)

这将为您提供预期的输出:

[1, 0, 2, 0, 3, 4, 5]
© www.soinside.com 2019 - 2024. All rights reserved.