【问题标题】:how to separate the list into nested list ,with the average of all elements in the list?如何将列表分成嵌套列表,列表中所有元素的平均值?
【发布时间】:2020-03-13 12:33:48
【问题描述】:

我需要将列表分成嵌套列表及其平均值。

 a =[ 0.6140781, 0.61407846, 0.6930427, 0.6930429, 0.7213439, 0.72134393, 0.7333274, 0.73332757]

列表的平均值为 0.05515

如果两个元素之间的差异不超过0.5515,我需要加入列表中的元素,如果列表中的下一个元素超过0.05515,则在python中形成另一个列表

想要的输出:

output : [[0.6140781, 0.61407846],[0.6930427, 0.69460429],[0.7213439, 0.72334393], [0.7333274, 0.73532757]]

任何建议都会有所帮助!

【问题讨论】:

  • 您的列表的平均值错误

标签: python-3.x list nested-lists


【解决方案1】:

由于列表已排序,可以迭代,如果当前元素大于目标值,则在输出中添加一个新列表,并将当前元素添加到最近添加的列表中。

您的输出与您提供的平均数没有意义,因为0.7213439 - 0.69460429 不大于 0.05515,0.7333274 - 0.72334393 也不大于所以我使用了 0.01。

a = [0.6140781, 0.61407846, 0.6930427, 0.6930429, 0.7213439, 0.72134393, 0.7333274, 0.73332757]

output = [a[:1]]

for i in range(1, len(a)):
    if a[i] - a[i-1] > 0.01:
        output.append([])
    output[-1].append(a[i])

print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2022-11-02
    • 2020-07-12
    • 2019-03-27
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多