我創建了一個通用函式來處理給定整數串列中 n 長度的連續配對,并將它們提供給一個函式。它有效,但我非常不喜歡函式中的 eval 但不知道如何更改它并仍然使用 zip 函式。
from typing import List
def consecutive_element_pairing(data: List[int], consecutive_element=3, map_to_func=sum) -> List[int]:
"""
Return a list with consecutively paired items given to a function that can handle an iterable
:param data: the list of integers to process
:param consecutive_element: how many to group consecutively
:param map_to_func: the function to give the groups to
:return: the new list of consecutive grouped functioned items
"""
if len(data) < consecutive_element:
return []
return list(map(map_to_func, eval("zip(%s)" % "".join((map(lambda x: "data[%d:], " % x, range(consecutive_element)))))))
給出一個串列,例如:
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
我這樣稱呼它:
print("result:", consecutive_element_pairing(values))
[6, 9, 12, 15, 18, 21, 24]
這是正確的,因為它正確地將((1,2,3),(2,3,4),(3,4,5)...)它們按連續的 3 組分組,然后將它們相加。
我的代碼遇到的問題是生成的zip(data[0:], data[1:], data[2:], ).
我不知道如何以不同的方式執行此操作,因為帶有串列的 zip 會執行完全不同的操作。
在仍然使用 zip 的同時,這可以以不同的方式完成嗎?
任何幫助表示贊賞。
我知道如何以多種不同的方式執行此操作,但我自己面臨的挑戰是在此處使用 zip :-) 并將其設為“通用”功能。
uj5u.com熱心網友回復:
您可以簡單地使用zip(*(values[i:] for i in range(N))):
例子
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
N = 3
list(zip(*(values[i:] for i in range(N))))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
長串列和大 N 的稍微改進的變體可能是:
zip(*(values[i:len(values)-(N-i) 1] for i in range(N)))
功能
from typing import List
def consecutive_element_pairing(data: List[int], consecutive_element=3, map_to_func=sum) -> List[int]:
N = consecutive_element
return list(map(map_to_func, zip(*(data[i:len(data)-(N-i) 1] for i in range(N)))))
consecutive_element_pairing(values)
# [6, 9, 12, 15, 18, 21, 24]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371024.html
