Skip to main content
 首页 » 编程设计

python之如何制作一个遍历 Python 列表的函数

2025年05月04日8lvdongjie

我用两个独立的传感器进行了测量。由于某种原因,其中一个传感器在测试期间变坏了,我想制作一个新列表,其中包含 sensor1 的前五个元素和 sensor2 的其余元素>。我设法简单地做到了这一点:

updated = []             
index   = 0 
while index < len(sensor1): 
    if index <= 2: 
        updated.append(sensor1[index]) 
    elif index > 2: 
        updated.append(sensor2[index]) 
    else: 
        print('You did something wrong, you ignorant fool!') 
    index += 1 

但是,为了更习惯Python,我想将其翻译成一个名为Updater的函数

def Updater(one, two, divide): 
    updated = [] 
    index   = 0 
    while index < len(one): 
        if index <= divide: 
            updated.append(one[index]) 
        elif index > divide: 
            updated.append(two[index]) 
        else: 
            print('You did something stupid, you ignorant fool!') 
        index += 1 
        return updated 

我称之为

data = Updater(one=sensor1, two=sensor2, divide=4) 

或

data = [Updater(a, b, divide=4) for a, b in zip(sensor1, sensor2)] 

唉,Updater 不起作用,因为它只执行第一次迭代,所以 index 等于 1,尽管它应该等于13,即sensor1和sensor2的长度。

  • 我做错了什么?
  • 如何让这段特定的代码在一个函数中运行?

请您参考如下方法:

问题是您在第一次迭代时返回了 updated。

此外,你可以这样做

result = one[:divide] + two[divide:]