Py学习  »  Python

在下一个子列表中添加新元素,这取决于python是否添加了新元素(还涉及字典问题)

Arnoldo Oliva • 3 年前 • 1255 次点击  

Stackoverflow社区:

我试图创建一个带有循环的子列表,该循环基于对另一个列表的值的随机抽样;每个子列表都有一个限制,即不能有一个重复项或一个已经添加到先前子列表中的值。

比如说,我有一个主要列表:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

#I get:
[[1,13],[4,1],[8,13]]

#I WANT:
[[1,13],[4,9],[8,14]]          #(no duplicates when checking previous sublists)

我认为它会起作用的真正代码如下(作为草稿):

matrixvals=list(matrix.index.values)  #list where values are obtained
lists=[[]for e in range(0,3)]         #list of sublists that I want to feed
vls=[]                                #stores the values that have been added to prevent adding them again
for e in lists:                       #initiate main loop
    for i in range(0,5):              #each sublist will contain 5 different random samples
        x=random.sample(matrixvals,1) #it doesn't matter if the samples are 1 or 2
        if any(x) not in vls:         #if the sample isn't in the evaluation list
            vls.extend(x)
            e.append(x)
        else:             #if it IS, then do a sample but without those already added values (line below)
            x=random.sample([matrixvals[:].remove(x) for x in vls],1)
            vls.extend(x)
            e.append(x)

        
print(lists)
print(vls)

当我得到以下信息时,它不起作用:

[[[25], [16], [15], [31], [17]], [[4], [2], [13], [42], [13]], [[11], [7], [13], [17], [25]]]
[25, 16, 15, 31, 17, 4, 2, 13, 42, 13, 11, 7, 13, 17, 25]

正如你所见,数字13重复了三次,我不明白为什么

我想要:

[[[25], [16], [15], [31], [17]], [[4], [2], [13], [42], [70]], [[11], [7], [100], [18], [27]]]
[25, 16, 15, 31, 17, 4, 2, 13, 42, 70, 11, 7, 100, 18, 27]   #no dups

此外,是否有一种方法可以转换样本。随机结果作为值而不是列表?(获取):

[[25,16,15,31,17]], [4, 2, 13, 42,70], [11, 7, 100, 18, 27]]

此外,实际上最终的结果不是子列表列表,实际上是一个字典(上面的代码是解决dict问题的一个尝试草案),有没有办法在dict中获得之前的方法?用我现在的代码,我得到了下一个结果:

{'1stkey': {'1stsubkey': {'list1': [41,
    40,
    22,
    28,
    26,
    14,
    41,
    15,
    40,
    33],
   'list2': [41, 40, 22, 28, 26, 14, 41, 15, 40, 33],
   'list3': [41, 40, 22, 28, 26, 14, 41, 15, 40, 33]},
  '2ndsubkey': {'list1': [21,
    7,
    31,
    12,
    8,
    22,
    27,...}

我想要的不是这个结果,而是:

 {'1stkey': {'1stsubkey': {'list1': [41,40,22],
       'list2': [28, 26, 14],
       'list3': [41, 15, 40, 33]},
      '2ndsubkey': {'list1': [21,7,31],
       'list2':[12,8,22],
       'list3':[27...,...}#and so on 

有没有办法同时解决列表和dict问题?任何帮助都将不胜感激;即使只有列表问题,我也能取得一些进展

谢谢大家

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129290
 
1255 次点击  
文章 [ 1 ]  |  最新文章 3 年前