簡體   English   中英

從Python列表中選擇隨機項目

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

我有一個不同長度的列表清單。 從列表的每個列表中,我需要隨機選擇10個項目。 然后,我必須將結果合並在一個列表中,每個列表項都用逗號分隔。 (請參見下面的輸出)。 不確定在Python中是否可行。 任何幫助,將不勝感激。

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

我想以適合於使用Folium在地圖上繪制它們的這種格式獲得輸出。

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

我嘗試了這段代碼,但不確定出了什么問題:

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

像這樣的事情很容易使用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

樣本數據(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]]
]

接着:

>>> 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()從給定的輸入(在我們的示例中為列表)中選擇一個隨機項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM