我是一名 Python 初學者,我已經撰寫了一些有效的代碼(顯示在最后),但我更愿意學習一種 Python 的方式來做到這一點。
我有一個元組串列,如下所示。每個串列中可能有 1 到 6 個元組。我想確定每個串列中三個數值的平均值,最后每個串列中只有一個元組,所以類似于第二個片段。
[
[
("2022-02-21 20:30:00", None, 331.0),
("2022-02-21 21:00:00", None, 324.0),
("2022-02-21 21:30:00", None, 298.0),
],
[
("2022-02-21 22:00:00", None, 190.0),
("2022-02-21 22:30:00", None, 221.0),
("2022-02-21 23:00:00", None, 155.0),
],
[
("2022-02-21 23:30:00", None, 125.0),
("2022-02-22 00:00:00", None, 95.0),
("2022-02-22 00:30:00", None, 69.0),
],
]
[
[
("2022-02-21 20:30:00", None, 317.7),
],
[
("2022-02-21 22:00:00", None, 188.7),
],
[
("2022-02-21 23:30:00", None, 96.3),
],
]
for li in data:
li = [list(t) for t in li]
sum = 0
for t in li:
sum = sum t[tuple_idx]
mean = sum / len(li)
li[0][tuple_idx] = mean
new_data.append(tuple(li[0]))
data = new_data
uj5u.com熱心網友回復:
我不會嘗試使它更 Pythonic 或更短但更具可讀性。
所以我會保留你的版本,只做一些小的改動。
首先,我會使用有意義的名稱。
并且有函式sum(),所以我不會將它用作變數。
new_data = []
value_idx = 2
for group in data:
total_sum = sum(item[value_idx] for item in group)
mean = total_sum / len(group)
first_item = list(group[0])
first_item[value_idx] = mean
new_data.append( [tuple(first_item)] )
data = new_data
uj5u.com熱心網友回復:
這可能是你能得到的最 Pythonic 的:
from statistics import fmean
result = [
[(*x[0][:-1], fmean(map(lambda y: y[2], x)))] for x in inputs
]
如果需要,可以通過將方括號放在推導式中,將其展平為元組串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430301.html
