list question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • python101
    New Member
    • Sep 2007
    • 90

    list question

    I would like to write a program count the items that appear in BOTH list
    [code=python]
    A=['A', 'B', 'C','D', 'F','G', 'H']
    B=['FF', 'GG', 'A','B', 'DD','EE', 'GG']

    for i in range(len(A)):
    count=0
    for k in range(len(B)):
    if A[i]==B[k]:
    count+=1

    count
    [/code]
    the result is 0 but it should be 2 (for 'A' and 'B')
    What did I do wrong?
  • dazzler
    New Member
    • Nov 2007
    • 75

    #2
    Originally posted by python101
    What did I do wrong?
    you put the count=0 in the wrong place ;)

    [code=python]
    A=['A', 'B', 'C','D', 'F','G', 'H']
    B=['FF', 'GG', 'A','B', 'DD','EE', 'GG']

    count=0
    for i in range(len(A)):
    for k in range(len(B)):
    if A[i]==B[k]:
    count+=1

    print count
    [/code]

    Comment

    • rogerlew
      New Member
      • Jun 2007
      • 15

      #3
      How about this:
      [code=python]
      count=0
      for a in A:
      if a in B: count+=1
      print count
      [/code]
      or this:
      [code=python]
      count=sum([1 for a in A if a in B])
      print count
      [/code]

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        Code:
        >>> A=['A', 'B', 'C','D', 'F','G', 'H']
        >>> B=['FF', 'GG', 'A','B', 'DD','EE', 'GG']
        >>> A+B
        ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'FF', 'GG', 'A', 'B', 'DD', 'EE', 'GG']
        >>> (A+B).count("A")
        2
        >>> (A+B).count("B")
        2
        >>>

        Comment

        • rogerlew
          New Member
          • Jun 2007
          • 15

          #5
          Originally posted by ghostdog74
          Code:
          >>> A=['A', 'B', 'C','D', 'F','G', 'H']
          >>> B=['FF', 'GG', 'A','B', 'DD','EE', 'GG']
          >>> A+B
          ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'FF', 'GG', 'A', 'B', 'DD', 'EE', 'GG']
          >>> (A+B).count("A")
          2
          >>> (A+B).count("B")
          2
          >>>
          Neat trick, but Python101 is looking for a method of counting items common to both lists.

          Comment

          • ghostdog74
            Recognized Expert Contributor
            • Apr 2006
            • 511

            #6
            Originally posted by rogerlew
            Neat trick, but Python101 is looking for a method of counting items common to both lists.
            yes, my bad. wrong interpretation.

            Comment

            Working...