打印列表的前 n 个不同值

我想从列表中打印前 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

我缺少什么?


沧海一幻觉
浏览 210回答 3
3回答

红糖糍粑

使用 numpyimport numpy as nptop=10test=[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])

大话西游666

我的解决方案test = [1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]uniqueList = [num for num in set(test)] #creates a list of unique characters [1,2,3,4,5,6,7,8,9,10,11,12,13]for num in range(0,11):    if uniqueList[num] != 1: #skips one, since you wanted to start with two        print(uniqueList[num])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python