List index method for complex list item types?

techiepundit at futurepundit.com techiepundit at futurepundit.com
Fri Dec 30 20:13:22 EST 2005


I'm a Python newbie who just started learning the language a few weeks
ago. So these are beginner questions.

I have a list of sockets that I use for select.select calls like this:

ReadList,WriteList,EventList = select.select(self.SocketList,[],[],3)

In parallel with that list of sockets I want something that is like a
list of socket,PacketFragment pairs. I need this because I could do
recv and get part of a sent packet. I want to loop around and each time
add more to the fragment until I get a full packet which has an
internal byte structure of the types I'm expecting.

The idea is every time I do
   self.SocketList.append(NewSocket)
also do
   self.SocketPacketFragmentList.append((NewSocket,''))
 so that the index into SocketList is the same as the index into
SocketPacketFragmentList. So I can use
self.SocketList.index(SomeSocket) find an item in SocketList and then
know how to find it in the other list.

MySocketIndex = self.SocketList.index(MyTargetSocket)

Then do:

MySubList = self.SocketPacketFragmentList[MySocketIndex]

Then

MyPacketFragment = MySubList[1]

But a thought struck me while writing this: Does Python not provide a
way to search a list of sublists to find something on, say, the value
of the first sublist item field as a way to find the index to the item
one wants in the parent list?

There does not appear to be an alternative to lists that has better
functionality for this purpose. Dictionaries are immutable, right? One
can't use dictionaries for doing look-ups on dynamically changing
lists?

For efficiency's sake it seems to me one wants a search function on
lists that returns two things:
   - index where the item found.
   - full item which matches on the particular field one is looking up
on.

Am I wrong in thinking Python doesn't really provide an automated way
to search lists of complex things?

Also, ii C++ one can use STL iterators to move thru a list or deque.
But if one needs to advance thru a list with array indexes that does
Python index in each time if one is looping thru the list?

In Python maybe the trick is to use
  ii = 0
  For item in List
     # see if item matches

    ii = ii + 1

and then somehow pop out of the for loop once one finds a match?




More information about the Python-list mailing list