Heim  >  Fragen und Antworten  >  Hauptteil

如何统计python list中元素的个数及其位置?

假设有一个list是[2,1,4,1,5,1,6,1],如果我想统计这个list中有多少个1,以及每个1的位置,应该如何写呢?谢谢~~

PHP中文网PHP中文网2741 Tage vor446

Antworte allen(1)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:29:49

    计数count,位置index

    a = [1,2,3,1]
    a.count(1) # 2
    a.index(1) # 0
    [x for x in range(len(a)) if a[x] == 1] # 一次获得所有位置

    Antwort
    0
  • StornierenAntwort