我是Python新手,擁有數字列表。例如 5,10,32,35,64,76,23,53...
。訪問數組中的分組項
我已經使用this post的代碼將它們分成了四個(5,10,32,35
,64,76,23,53
等..)。
def group_iter(iterator, n=2, strict=False):
""" Transforms a sequence of values into a sequence of n-tuples.
e.g. [1, 2, 3, 4, ...] => [(1, 2), (3, 4), ...] (when n == 2)
If strict, then it will raise ValueError if there is a group of fewer
than n items at the end of the sequence. """
accumulator = []
for item in iterator:
accumulator.append(item)
if len(accumulator) == n: # tested as fast as separate counter
yield tuple(accumulator)
accumulator = [] # tested faster than accumulator[:] = []
# and tested as fast as re-using one list object
if strict and len(accumulator) != 0:
raise ValueError("Leftover values")
如何訪問單個數組以便我可以對它們執行功能。例如,我想得到每個組的第一個數值的平均值(例如我的示例中的數字爲5 and 64
)。
您正在重新定義'list',它是一個標準的類名。不建議。 –
是的,我通常會避免這樣做,但python語法突出顯示有助於示例。 – inlinestyle