我有一系列不同长度的列表。从每个列表列表中,我需要随机选择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)
答案 0 :(得分:1)
使用模块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]]
答案 1 :(得分:0)
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()
从给定输入中选择一个随机项(在我们的例子中是一个列表)。