简体   繁体   English

从Python列表中选择随机项目

[英]Select random items from list of lists in Python

I have a list of lists of different lengths. 我有一个不同长度的列表清单。 From each list of lists, I need to randomly select 10 items. 从列表的每个列表中,我需要随机选择10个项目。 Then I have to combine the results in a single list with each list item separated by comma. 然后,我必须将结果合并在一个列表中,每个列表项都用逗号分隔。 (Pls see the output below). (请参见下面的输出)。 Not sure whether this is possible in Python. 不确定在Python中是否可行。 Any help would be appreciated. 任何帮助,将不胜感激。

[[-26.0490761  27.79991  ]
 [-25.9444218  27.9116535]
 [-26.1055737  27.7756424]
 ..., 
 [-26.036684   28.0508919]
 [-26.1367035  28.2753029]
 [-26.0668163  28.1137161]]

[[ 45.35693   -63.1701241]
 [ 44.6566162 -63.5969276]
 [ 44.7197456 -63.48137  ]
  ..., 
 [ 44.624588  -63.6244736]
 [ 44.6563835 -63.679512 ]
 [ 44.66706   -63.621582 ]]

I would like to get the output in this format that is suitable for plotting them on a map using Folium. 我想以适合于使用Folium在地图上绘制它们的这种格式获得输出。

 [[-26.0490761  27.79991],
  [-25.9444218  27.9116535],
  [ 44.6563835 -63.679512 ],
  [ 44.66706   -63.621582 ]]

I tried this code but not sure what went wrong: 我尝试了这段代码,但不确定出了什么问题:

  for cluster in clusters:
    for i in range(2):
       modifiedlist.append(cluster)

Something like this is easy using the module random : 像这样的事情很容易使用random模块:

import random

def sampleFromLists(lists,n):
    """draws n elements from each list in lists
returning the result as a single list"""
    sample = []
    for subList in lists:
        sample.extend(random.sample(subList,n))
    return sample

Sample data (a list of lists of 2-element lists): 样本数据(2元素列表的列表):

data = [
    [[-26.0490761, 27.79991],
     [-25.9444218, 27.9116535],
     [-26.1055737, 27.7756424],
     [-26.036684, 28.0508919],
     [-26.1367035, 28.2753029],
     [-26.0668163,28.1137161]],

    [[ 45.35693, -63.1701241],
     [44.6566162 -63.5969276],
     [44.7197456, -63.48137],
     [44.624588, -63.6244736],
     [44.6563835,-63.679512],
     [44.66706, -63.621582]]
]

And then: 接着:

>>> sampleFromLists(data,2)
[[-26.036684, 28.0508919], [-26.0490761, 27.79991], [44.7197456, -63.48137], [44.6563835, -63.679512]]
import random

x = [[1,2],[3,4],[5,6],[7,8],[9],[7675,6456,4],[5,6]]

z = []
for i in range(10):
  y = random.choice(x)
  z.append([random.choice(y), random.choice(y)])

print(z)

random.choice() picks a random item from the given input (in our case a list). random.choice()从给定的输入(在我们的示例中为列表)中选择一个随机项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM