Python 打印列表的前n个不同值
我想打印列表中前10个不同的元素:Python 打印列表的前n个不同值,python,python-3.x,for-loop,Python,Python 3.x,For Loop,我想打印列表中前10个不同的元素: top=10 test=[1,1,1,2,3,4,5,6,7,8,9,10,11,12,13] for i in range(0,top): if test[i]==1: top=top+1 else: print(test[i]) 它正在印刷: 2,3,4,5,6,7,8 我期待着: 2,3,4,5,6,7,8,9,10,11 我遗漏了什么?因为您编写的代码只执行循环10次,前3次用于忽略1,所以只打印以
top=10
test=[1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in range(0,top):
if test[i]==1:
top=top+1
else:
print(test[i])
它正在印刷:
2,3,4,5,6,7,8
我期待着:
2,3,4,5,6,7,8,9,10,11
我遗漏了什么?因为您编写的代码只执行循环
10次,前3次用于忽略1
,所以只打印以下3次,这正是这里发生的
如果要打印前10个不同的值,我建议您这样做:
# The code of unique is taken from [remove duplicates in list](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists)
def unique(l):
return list(set(l))
def print_top_unique(List, top):
ulist = unique(List)
for i in range(0, top):
print(ulist[i])
print_top_unique([1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 10)
我的解决方案
使用numpy
import numpy as np
top=10
test=[1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]
test=np.unique(np.array(test))
test[test!=1][:top]
输出
array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
您缺少索引i
应采用值0,1,9
,但前10个不同元素的索引值应为0、1、2、3、4、5、6、7、8、9、10、11、12、13
。如果需要前10个不同值,则输出应为1、2、3、4、5、6、7、8、9、10
。为什么会是2,3,4,5,6,7,8,9,10,11
?我认为set()
不会一直保持秩序
array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])