【问题标题】:Set of float numbers, append numbers to empty list in sets . Python一组浮点数,将数字附加到 sets 中的空列表。 Python
【发布时间】:2012-11-19 22:52:12
【问题描述】:

一组数字

n_set = [1.0,3.2,4.5,8.2,1.3,2.2,5.6,9.8,2.4,5.5,6.7]

所以我正在尝试构建一个函数,该函数接受一组数字并从数字集中创建一个列表列表。我试图让每个列表都有一个原始集合中的数字子集,这些数字会增加直到达到最大值

organized_set = [[1.0,3.2,4.5,8.2],[1.3,2.2,5.6,9.8],[2.4,5.5,6.7]]

我在想一些类似的事情

for i,k in zip(range(0,len(n_set)),n_set):
    set = []
    d = dict(zip(i,k))
    d2 = dict(zip(k,i))
    if d[i] < d[d2[i]+1]:
        set.append(k)

这没有意义。我正在研究一个更复杂的功能,但这是让我失望的一部分。任何帮助将不胜感激

【问题讨论】:

    标签: python list function append max


    【解决方案1】:

    尝试类似这样的迭代方法:

    n_set = [1.0,3.2,4.5,8.2,1.3,2.2,5.6,9.8,2.4,5.5,6.7]
    
    prev = None
    result = []
    current = []
    for x in n_set:
        if prev is not None and x < prev:
            # Next element is smaller than previous element.
            # The current group is finished.
            result.append(current)
    
            # Start a new group.
            current = [x]
        else:
            # Add the element to the current group.
            current.append(x)
    
        # Remember the value of the current element.
        prev = x
    
    # Append the last group to the result.
    result.append(current)
    
    print result 
    

    结果:

    [[1.0, 3.2, 4.5, 8.2], [1.3, 2.2, 5.6, 9.8], [2.4, 5.5, 6.7]]
    

    【讨论】:

    • 太棒了!非常感谢。我对几个部分的工作方式有点困惑。 . . 1] 当您分配 prev = None 因为“如果 x
    • @draconisthe0ry:我更新了我的答案并在代码中添加了一些 cmets。我希望这会有所帮助。如果您仍然遇到问题,请尝试安装具有调试支持的 IDE,并逐行查看代码以查看其工作原理。
    【解决方案2】:
         python 3.2
    
         temp=[]
         res=[]
    
         for i in n:
              temp.append(i)
              if len(temp)>1 and i<temp[-2]:
                      res.append(temp[:-1])
                      temp=[i]
         res.append(temp)
         print(res)
    

    【讨论】:

      猜你喜欢
      • 2014-02-01
      • 1970-01-01
      • 2018-09-25
      • 2017-03-06
      • 2013-03-22
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      相关资源
      最近更新 更多