可以将 for i in range loop on i, i+1 重写为 for i in loop in Python 吗?
Possible to rewrite for i in range loop on i, i+1 into for i in loop in Python?
是否可以重写下面的循环:
from typing import List
def adjacentElementsProduct(inputArray: List[int]) -> int:
product_list = []
for i in range(len(inputArray) - 1):
product_list.append(inputArray[i] * inputArray[i+1])
return max(product_list)
变成这样的东西:
for i in inputArray:
product_list.append(i, the thing after i)
如果有任何帮助,您可以创建一个生成器函数来帮助您执行此操作:
def pairs(seq):
it = iter(seq)
val1 = next(it)
for val2 in it:
yield val1, val2
val1 = val2
for x, y in pairs(range(10)):
print(f"x={x} y={y}")
给出:
x=0 y=1
x=1 y=2
x=2 y=3
x=3 y=4
x=4 y=5
x=5 y=6
x=6 y=7
x=7 y=8
x=8 y=9
您可以 zip
序列自身的移位版本:
seq = ['a', 'b', 'c', 'd', 'e', 'f']
for i, j in zip(seq, seq[1:]):
print(i, j)
输出:
a b
b c
c d
d e
e f
要获取所有相邻对,您可以使用 zip
pairs = zip(inputArray, inputArray[1:])
然后你可以使用 max
并传递给它另一个生成器,将对相乘以获得最大总和
max(a * b for a, b in pairs)
您可以通过删除中间列表来缩短它,但是任何更多的东西都会掩盖您正在做的事情。
def adjacentElementsProduct(inputArray: List[int]) -> int:
return max(inputArray[i] * inputArray[i+1]
for i in range(len(inputArray) - 1))
是否可以重写下面的循环:
from typing import List
def adjacentElementsProduct(inputArray: List[int]) -> int:
product_list = []
for i in range(len(inputArray) - 1):
product_list.append(inputArray[i] * inputArray[i+1])
return max(product_list)
变成这样的东西:
for i in inputArray:
product_list.append(i, the thing after i)
如果有任何帮助,您可以创建一个生成器函数来帮助您执行此操作:
def pairs(seq):
it = iter(seq)
val1 = next(it)
for val2 in it:
yield val1, val2
val1 = val2
for x, y in pairs(range(10)):
print(f"x={x} y={y}")
给出:
x=0 y=1
x=1 y=2
x=2 y=3
x=3 y=4
x=4 y=5
x=5 y=6
x=6 y=7
x=7 y=8
x=8 y=9
您可以 zip
序列自身的移位版本:
seq = ['a', 'b', 'c', 'd', 'e', 'f']
for i, j in zip(seq, seq[1:]):
print(i, j)
输出:
a b
b c
c d
d e
e f
要获取所有相邻对,您可以使用 zip
pairs = zip(inputArray, inputArray[1:])
然后你可以使用 max
并传递给它另一个生成器,将对相乘以获得最大总和
max(a * b for a, b in pairs)
您可以通过删除中间列表来缩短它,但是任何更多的东西都会掩盖您正在做的事情。
def adjacentElementsProduct(inputArray: List[int]) -> int:
return max(inputArray[i] * inputArray[i+1]
for i in range(len(inputArray) - 1))