一组浮点数,将数字追加到集合中的空列表。Python

2024-06-07 19:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

一组数字

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)

这没道理。我正在研究一个复杂得多的函数,但这是其中的一部分,让我很失望。任何帮助都将不胜感激


Tags: 函数in列表forlenifrange数字
2条回答

尝试这样的迭代方法:

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]]
     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)

相关问题 更多 >

    热门问题