如何从数组中删除随机元素。蟒蛇

时间:2018-09-13 21:44:34

标签: python arrays python-3.x logic conditional

所以我将首先解释问题的背景。

我有一个由多个字符串填充的数组,我想从该数组中选择随机元素,但是一旦选择了一个元素,就无法再次选择它。我的解决方案是简单地将其从数组中删除。

我尝试过:

Excel.SeriesCollection threshold = sChartCPU.sseriesCollection();
Excel.Series line = threshold.NewSeries();

// line.Formula = "=SERIES(Summ!$D$54,Summ!$C$55:$C$56,Summ!$D$55:$D$56)";
// instead of setting the Formula, I set the series values
line.Values = "='Summ!'$D$55:$D$56";
line.XValues = "='Summ!'$C$55:$C$56";

line.ChartType = Excel.XlChartType.xlXYScatterLinesNoMarkers;


// creates Axis objects for the secondary axes
Excel.Axis YAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlSecondary);
Excel.Axis XAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlSecondary);

// remove the major and minor tick marks from the secondary (top) x-axis
XAxis2.MajorTickMark = Excel.XlTickMark.xlTickMarkNone;
XAxis2.MinorTickMark = Excel.XlTickMark.xlTickMarkNone;

// change the secondary x-axis max range to 1.0 so the bar will go all the way to the right side
XAxis2.MaximumScale = 1.0;

// delete the secondary x-axis labels 
XAxis2.TickLabels.Delete();

// I chose to delete the secondary y-axis so the line would graph on the primary axis scale
YAxis2.Delete();

但是我收到错误:ValueError:list.remove(x):x不在列表中

我该怎么办?

3 个答案:

答案 0 :(得分:1)

如果您愿意为此使用numpy,则函数np.random.choice允许您选择样本的大小,而不是像尝试那样循环遍历range(3),并且参数replace=False保证您不会两次选择相同的对象:

import numpy as np

dogs_array =['Bob', 'Fred', 'Jeff', 'Rick', 'Alice', 'Joe','Max', 'Will']

my_selection = np.random.choice(dogs_array, size=3, replace=False)

>>> my_selection
array(['Fred', 'Alice', 'Jeff'], dtype='<U5')

答案 1 :(得分:1)

如何使用pop方法,非常适合您在这里做的事情:

import random

dogs = ['Bob', 'Fred', 'Jess', 'Rick', 'Alice', 'Joe', 'Max', 'Will']

for x in range(3):
    selection = random.randint(0, len(dogs)-1)
    goner = dogs.pop(selection)
    print(goner)

输出

(xenial)vash@localhost:~/python$ python3.7 pop.py
Max
Bob
Joe

使用pop时,由于列表将更改大小,因此您将需要使用len,并且对于该新列表大小,您将需要一个随机整数。

答案 2 :(得分:1)

对于那些寻找问题答案的人(np.array,而不是list :)),这可能会有帮助

file << (int)rgb.rgbtBlue << ",";