Python- How to form a random partition of 2 lists [closed]

痞子三分冷 提交于 2019-12-13 22:05:55

问题


Does anyone know how to form a random partition of 2 lists (List1 and List2) in python? The lists do not have to have the same size. For example:

S = [1,2,3,4,5,6,7]
List1=[3,6,1,2]
List2=[5,4,7]

or

List1 =[3,5]
List2=[1,2,4,7,6]

回答1:


I'm not sure what your rules are around randomness and partitioning, but this should get you started:

import random

s = [1,2,3,4,5,6,7]

random.shuffle(s)

cut = random.randint(0, len(s))
list_1 = s[:cut]
list_2 = s[cut:]

print list_1
print list_2



回答2:


I would recommend:

  1. Shuffle or randomly rearrange the list
  2. Then choose the random index at which to break up the list

Code:

import random

S = [1,2,3,4,5,6,7]
random.shuffle(S)
index = random.randint(0, len(S))
List1 = S[index:]
List2 = S[:index]



回答3:


Not sure what modules you have but this is a function that does what you want.

import random
def split(S): 
    x = random.randint(0,len(S))
    y = len(S)-x
    S1 = S[0:x]
    S2 = []
    for i in range(len(S)):
        if S[i] not in S1:
           S2.append(S[i])
    return S1,S2


来源:https://stackoverflow.com/questions/43196649/python-how-to-form-a-random-partition-of-2-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!