如何获取给定百分比范围内的列表元素



我正在尝试迭代满足我的不使用numPy的百分比范围。我正在用一个简单的for循环来处理这个问题。我得到的答案是我想要的所有元素,但它正在重复。我缺少什么?

yos = [('student3', 12),
('student4', 14),
('student9', 35),
('student6', 43),
('student1', 45),
('student7', 47),
('student5', 48),
('student2', 78),
('student10', 80),
('student8', 98)]

for si in range(25, 76):
y = len(yos)*(si/100)
y1 = int(y+.5)
if yos[y1-1] in yos:
print(yos[y1-1])


想要的输出:

('student9', 35)
('student6', 43)
('student1', 45)
('student7', 47)
('student5', 48)

接收输出:

('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student9', 35)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student6', 43)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student1', 45)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student7', 47)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student5', 48)
('student2', 78)

您的计算结果会产生重复值。

y = len(yos)*(si/100)
y1 = int(y+.5)

y1对于多次迭代将是相同的值。y=2.6,y=2.7,y=2.8,y=2.9当你加上.5并将其转换为整数时,所有这些都转换为3

一种选择是创建一组索引,然后打印出这些索引的值。

类似于:

import math

yos = [('student3', 12),
('student4', 14),
('student9', 35),
('student6', 43),
('student1', 45),
('student7', 47),
('student5', 48),
('student2', 78),
('student10', 80),
('student8', 98)]

set_of_indices = set([int(math.floor(len(yos) * (si / 100))) for si in range(25, 76)])
for y in set_of_indices:
print(yos[y])
z = [('student3', 12),
('student4', 14),
('student9', 35),
('student6', 43),
('student1', 45),
('student7', 47),
('student5', 48),
('student2', 78),
('student10', 80),
('student8', 98)]

for si in range(25, 75,10):
y = (len(z)*si)/100
y1 = int(y+.5)
if z[y1-1] in z: print(z[y1-1])

试试这里的代码

实际上是int((函数造成了这个问题。因此,解决方案是添加10作为范围内的第三个参数:range(25, 75,10)要了解更多信息,请参阅.range()功能文档

你还必须使范围在2575之间,而不是76。。。所以.int((没有问题

最新更新