Comparing lists

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pystarter
    New Member
    • May 2012
    • 6

    Comparing lists

    Say I have two lists:

    list1 = [A, B, C, D, E]
    list2 = [A|1, C|2, D|2, F|3]

    I want to compare if the entries in list1 exist in the first half of the list2 entries, and print the whole outcome from list2.

    So from this I would want an outcome of:

    A|1, C|2, D|2

    Thanks in advance.
  • BadOPCode
    New Member
    • May 2012
    • 3

    #2
    Well... your syntax I think is a bit off if i'm understanding you correctly. I think this is what you want...

    Code:
    list1 = ['A', 'B', 'C', 'D', 'E']
    list2 = {'A':1, 'C':2, 'D':2, 'F':3}
    for i in list1:
         if list2.has_key(i):
                 print i+':'+str(list2[i])
    list2 is actually a dictionary. Am I sorta close to what you were looking for?

    Comment

    • pystarter
      New Member
      • May 2012
      • 6

      #3
      Sorry I possibly didn't explain too well!

      It's close - although I already have both the lists ready to compare, and the second one is in the format I wrote, ie - A|1, B|2 etc.

      Any way around that?

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        You should post some code to get help. Any forum will be overwhelmed with requests if it starts providing free code for anyone who asks.

        list1 contains five variables, so you want to compare the value associated with these variables to list2, but list2 does not make any sense as what it contains is neither a variable or a string. You have to ask good questions (and at least make a good attempt at coding it) to get good answers. If list2 could contain strings, then you can convert it to a set and test each value in list1 for membership in the set.
        Code:
        list_2 =['A|1', 'C|2', 'D|2', 'F|3']
        set_2 = set([x.split("|")[0] for x in list_2])
        print set_2
        Some info on variables and traversing a list.

        Comment

        • Rabbit
          Recognized Expert MVP
          • Jan 2007
          • 12517

          #5
          Why would your results return D? It's not in the first half and you said you only wanted the first half.

          Comment

          Working...