简体   繁体   中英

Get the intersections of a list and list of Tuples

two list

ListOne = ['steve','rob','jym','rich','bell','mick']
ListTwo = [('steve',22 ,178), ('rob', 23 ,189), ('jym', 25,165), ('steven',18 ,187), ('Manro',16 ,200), ('bell',21 ,167), ('mick', 24 ,180)]

How can i get the just the data from ListTwo for the students on the ListOne something like two list intersections .

Output like :

ListTwo = [('steve',22 ,178), ('rob', 23 ,189), ('jym', 25,165), ('bell',21 ,167), ('mick', 24 ,180)]

I tried this, but I'm looking for something more officiant:

for row in ListTwo:   
    if row[0] in ListOne :
        print 'this student exist' + `row[0]`

    else :
        for i,e in enumerate(ListTwo):
        #Check the student with the above results, will be removed
            if row[0] == e: 
                temp=list(ListTwo[i])
                pprint.pprint('I will remove this student : ' + `e`)
                #Remove the Student
                for f, tmp in enumerate(temp):
                     temp[f]= []
                #pprint.pprint(temp)
                ListTwo[i]=tuple(temp)

Use a list comprehension :

[rec for rec in ListTwo if rec[0] in ListOne]

To make it faster, you can replace list-lookups with set-lookups, by first converting the list to a set :

ListOne = set(ListOne)

one way is numpy

import numpy
a = numpy.array(list2)
print a[numpy.in1d(a[:,0],list1)]

but I would probably do a list comprehension as advised by shx2 ... numpy will change your types

this would take column 0 of your 2d numpy array (which is the names of the tuples)

numpy.in1d would create a mask [True,False,etc] based on if the name is in the other list

then it takes the original array and uses boolean indexing

>>> a = numpy.array(ListTwo)
>>> a[numpy.in1d(a[:,0],ListOne)]
array([['steve', '22', '178'],
       ['rob', '23', '189'],
       ['jym', '25', '165'],
       ['bell', '21', '167'],
       ['mick', '24', '180']],
      dtype='|S6')
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM