lists with zero-valued elements

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nick Forest

    lists with zero-valued elements

    Any body knows a trivial way to enumerate a list with n zero-valued elements?
  • Skip Montanaro

    #2
    Re: lists with zero-valued elements


    Nick> Any body knows a trivial way to enumerate a list with n
    Nick> zero-valued elements?

    I'm not sure what you're asking. I'd enumerate a list with n zero-valued
    elements the same way I'd enumerate one with m zero-valued elements:

    nelements = len(somelist)

    If I wanted to count how many elements were zero, I might do something like:

    nzeros = 0
    for element in somelist:
    if element == 0:
    nzeros += 1

    or more succinctly:

    nzeros = len([element for element in somelist if element == 0])

    Skip

    Comment

    • Alex Martelli

      #3
      Re: lists with zero-valued elements

      Nick Forest wrote:
      [color=blue]
      > Any body knows a trivial way to enumerate a list with n zero-valued
      > elements?[/color]

      'enumerate'...? As in, enumerate(n*[0]) ... ?


      Alex

      Comment

      • Alex Martelli

        #4
        Re: lists with zero-valued elements

        Skip Montanaro wrote:
        ...[color=blue]
        > If I wanted to count how many elements were zero, I might do something
        > like:
        >
        > nzeros = 0
        > for element in somelist:
        > if element == 0:
        > nzeros += 1
        >
        > or more succinctly:
        >
        > nzeros = len([element for element in somelist if element == 0])[/color]

        I'd do somelist.count( 0) -- faster, more direct, and even more succint.


        Alex

        Comment

        Working...