我用两个独立的传感器进行了测量。由于某种原因,其中一个传感器在测试过程中坏了,我想创建一个新列表,其中包含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
的长度。你知道吗
我将使用
itertools
模块中已有的工具:islice(one, divide)
产生one
的前5个元素;islice(two, divide, None)
产生从two
开始的第6个元素的所有元素。chain
将两个迭代器连接在一起,list
构建对结果的迭代,并从看到的元素构建一个列表。你知道吗切片将在连接列表之前创建列表(部分)的副本。
islice
只返回一个迭代器,该迭代器只生成请求元素而不生成任何副本。这也适用于任意的iterables,而不仅仅是列表。你知道吗您还可以将创建具体列表的决定推迟给调用者:
如果您实际上不需要在内存中存储结果的完整列表,例如如果您只计划对其进行迭代,那么这将非常有用:
使用当前脚本:
我们得到以下输出:
这是因为
return
语句在while循环中,一旦循环执行一次,它将返回sensor\u 1中的第一个元素并立即退出循环。但是,将return
语句向后推一个缩进级别:输出:
问题是在第一次迭代时返回
updated
。你知道吗而且,你可以
相关问题 更多 >
编程相关推荐