为了账号安全,请及时绑定邮箱和手机立即绑定

打印列表的前 n 个不同值

打印列表的前 n 个不同值

沧海一幻觉 2021-09-14 15:10:35
我想从列表中打印前 10 个不同的元素:top=10test=[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我缺少什么?
查看完整描述

3 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

使用 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])


查看完整回答
反对 回复 2021-09-14
?
大话西游666

TA贡献1817条经验 获得超14个赞

我的解决方案

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])


查看完整回答
反对 回复 2021-09-14
  • 3 回答
  • 0 关注
  • 184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信