打印列表的前n个不同值

时间:2018-12-11 12:30:40

标签: 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

我想念什么?

3 个答案:

答案 0 :(得分:1)

由于您的代码仅执行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)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我的解决方案

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