【问题标题】:Printing top n distinct values of a list打印列表的前 n 个不同值
【发布时间】:2018-12-11 12:30:39
【问题描述】:

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

我错过了什么?

【问题讨论】:

  • 您错过了索引 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

标签: python python-3.x for-loop


【解决方案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】:

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

    【讨论】:

      【解决方案3】:

      我的解决方案

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

      【讨论】:

      • 我不认为set() 会一直保留订单
      猜你喜欢
      • 1970-01-01
      • 2019-11-13
      • 2010-10-27
      • 2018-06-29
      • 2023-03-19
      • 1970-01-01
      • 2019-02-02
      • 2013-03-14
      • 2021-03-30
      相关资源
      最近更新 更多