如何在Python中生成遍历列表的函数?

2024-03-29 12:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用两个独立的传感器进行了测量。由于某种原因,其中一个传感器在测试过程中坏了,我想创建一个新列表,其中包含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,也就是sensor1sensor2的长度。你知道吗

  • 我做错什么了?你知道吗
  • 如何使这段特定的代码在函数中工作?你知道吗

Tags: 元素indexlenif传感器oneupdatertwo
3条回答

我将使用itertools模块中已有的工具:

from itertools import chain, islice

def updater(one, two, divide):
    # Similar to return one[:divide] + two[divide:]
    return list(chain(islice(one, divide), islice(two, divide,  None)))

islice(one, divide)产生one的前5个元素;islice(two, divide, None)产生从two开始的第6个元素的所有元素。chain将两个迭代器连接在一起,list构建对结果的迭代,并从看到的元素构建一个列表。你知道吗

切片将在连接列表之前创建列表(部分)的副本。islice只返回一个迭代器,该迭代器只生成请求元素而不生成任何副本。这也适用于任意的iterables,而不仅仅是列表。你知道吗

您还可以将创建具体列表的决定推迟给调用者:

def updater(one, two, divide):
    return chain(islice(one, divide), islice(two, divide, None))

updated = list(updater(one, two, divide))

如果您实际上不需要在内存中存储结果的完整列表,例如如果您只计划对其进行迭代,那么这将非常有用:

for x in updater(one, two, 5):
    ...

使用当前脚本:

sensor_1 = [1,2,3,4,5]

sensor_2 = [6,7,8,9,20,22,23]

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

print(Updater(sensor_1, sensor_2, 2))

我们得到以下输出:

[1]

这是因为return语句在while循环中,一旦循环执行一次,它将返回sensor\u 1中的第一个元素并立即退出循环。但是,将return语句向后推一个缩进级别:

sensor_1 = [1,2,3,4,5]

sensor_2 = [6,7,8,9,20,22,23]

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

print(Updater(sensor_1, sensor_2, 2))

输出:

[1, 2, 3, 9, 20]

问题是在第一次迭代时返回updated。你知道吗

而且,你可以

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

相关问题 更多 >