473,395 Members | 1,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

[].index

Good day.
Recently I'd run into wishing a list's index method would match
substrings. Being fairly new to this game I can't help but think that my
solution is a little, well, clumsy. In the following trivial example I'm
only interested in finding the first matching list item:
data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo =
['b','e','e']
[data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for
ix in range(len(foo))]


['bbb', 'eee', 'eee']
So I guess this question is - have I missed a cleaner method then this
nested list comprehension?
Jul 18 '05 #1
4 1821
Mike Edey wrote:
Good day.
Recently I'd run into wishing a list's index method would match
substrings. Being fairly new to this game I can't help but think that my
solution is a little, well, clumsy. In the following trivial example I'm
only interested in finding the first matching list item:
data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo =
['b','e','e']
[data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for
ix in range(len(foo))]


['bbb', 'eee', 'eee']
So I guess this question is - have I missed a cleaner method then this
nested list comprehension?


This depends on what you need this for exactly. Will you always be matching
a single character to the beginning of a string or will they sometimes be
more than one character? if only one, then how about storing the strings as
a dict with the characters as keys?
Jul 18 '05 #2
Using your test case:
data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh']
foo = ['b', 'e', 'e']
I'd define a function to do the difficult part:
(note that in Python 2.3, "s in t" returns True if s is a substring of t.
In earlier versions, "s in t" worked only when s was a length-1 string) def match(substring, candidates): ... """Return the candidate which contains substring"""
... for c in candidates:
... if substring in c: return c

Then, the list comprehension becomes simple: [match(c, data) for c in foo] ['bbb', 'eee', 'eee']

Even if you want to write this as a single list comprehension, why not [iy for ix in foo for iy in data if ix in iy] ['bbb', 'eee', 'eee']
... though if some item in foo doesn't correspond to any items in data,
you just get a different-length output than input, not an exception (as
for your code) or a None in the resulting list (in my first example)

Personally, I'll take the approach that uses a function. The
pure-listocmp version I wrote might as well say [fee fie foe fum i smell the blood of an englishman]

as far as my eyes are concerned.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAu0XIJd01MZaTXX0RAlZsAJ0ZCAxaOdcgnYv6o/NgSyAhYN/cKQCeONd7
cvbvdpQ+Fjdm7KJgI4nHD/I=
=hWv7
-----END PGP SIGNATURE-----

Jul 18 '05 #3
Mike Edey wrote:
Good day.
Recently I'd run into wishing a list's index method would match
substrings. Being fairly new to this game I can't help but think that my
solution is a little, well, clumsy. In the following trivial example I'm
only interested in finding the first matching list item:

data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo =
['b','e','e']
[data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for
ix in range(len(foo))]

['bbb', 'eee', 'eee']
So I guess this question is - have I missed a cleaner method then this
nested list comprehension?


Here's an option:

[s for s in data for prefix in foo if s.startswith(prefix)]

Clearer to read and understand. I like to keep away from indexes and
counters as much as possible.

HTH,
Shalabh
Jul 18 '05 #4
>>>>> Mike Edey <mi**@edey.mine.nu> (ME) wrote:

ME> Good day.
ME> Recently I'd run into wishing a list's index method would match
ME> substrings. Being fairly new to this game I can't help but think that my
ME> solution is a little, well, clumsy. In the following trivial example I'm
ME> only interested in finding the first matching list item:
data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo =
['b','e','e']
[data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for
ix in range(len(foo))]


ME> ['bbb', 'eee', 'eee']
ME> So I guess this question is - have I missed a cleaner method then this
ME> nested list comprehension?

It can be cleaned up:

[d for d in data for x in foo if d.find(x) > -1]
--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.***********@hccnet.nl
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jofio | last post by:
Hello, I am a newbie in PHP and I am enthusiastically trying out things. I've just replaced my index.html ( file with index.php
9
by: kosh | last post by:
I was wondering if there is or there could be some way to pass a generator an optional starting index so that if it supported that slicing could be made more efficient. Right now if you do use a...
2
by: skura | last post by:
I am trying to understand how the data in sql server is stored and also regarding fill factor and page splitting. 1) My first question what is the difference between Index pages and Data pages....
6
by: Anita | last post by:
I have just tested 3 queries using QA. The complete test information : ------ CREATE TABLE agls1 ( fyear char(4) NULL , fprefix char(3) NULL , fvcno char(20) NULL , fdate datetime NULL ,...
8
by: Andr? Queiroz | last post by:
Hi, I have a table with 10M records and col A has a index created on it. The data on that table has the same value for col A on all 10M records. After that I insert diferent values for that column...
14
by: Sean C. | last post by:
Helpful folks, Most of my previous experience with DB2 was on s390 mainframe systems and the optimizer on this platform always seemed very predictable and consistent. Since moving to a WinNT/UDB...
4
by: Steph. | last post by:
I have a List view displaying data in Detail mode with several columns. How I can get the column index the user clicked on ? (when user click on an item inside the ListView, not on a column...
2
by: bobby_b_ | last post by:
I have a table where fields 1 and 2 make up the primary key. Because of this, I have a unique composite index on fields 1 and 2 (as required by DB2). Now my question is: Fields 1 and 2 are also...
85
by: Russ | last post by:
Every Python programmer gets this message occasionally: IndexError: list index out of range The message tells you where the error occurred, but it doesn't tell you what the range and the...
8
by: shira | last post by:
I have done a fair bit of searching, but haven't yet been able to find an explanation as to why one would set "ignore nulls" to "yes" when creating an index. I understand what it does (I think),...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.