473,698 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[].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','cc c','ddd','eee', 'fff','ggg','hh h'] 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 1833
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','cc c','ddd','eee', 'fff','ggg','hh h'] 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','cc c','ddd','eee', 'fff','ggg','hh h']
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)

iD8DBQFAu0XIJd0 1MZaTXX0RAlZsAJ 0ZCAxaOdcgnYv6o/NgSyAhYN/cKQCeONd7
cvbvdpQ+Fjdm7KJ gI4nHD/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','cc c','ddd','eee', 'fff','ggg','hh h'] 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(pr efix)]

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','cc c','ddd','eee', 'fff','ggg','hh h'] 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.n l>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.***********@h ccnet.nl
Jul 18 '05 #5

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

Similar topics

3
6080
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
2133
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 generator and do a or any other kind of slice it reads all the values up to 100 also. I know a lot of generators have to do all previous parts before they can do the next part but it would be a nice optimization that can start at any index to...
2
10348
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. and how are they different for clustered and non clustered indexes and heap tables. 2) What is the relation between index and data pages.
6
4453
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 , fid char(15) NULL ,
8
4838
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 but my queries do not use the index I created for that column. Is there any way I can force the usage of the index or to ommit a value on the index creation, like 0 (zeroes) or spaces? Thanks in advance, André Queiroz
14
5409
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 7.2 environment, the choices the optimizer makes often seem flaky. But this last example really floored me. I was hoping someone could explain why I get worse response time when the optimizer uses two indexes, than when it uses one. Some context:
4
10679
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 hearder..) Thanks for any help !
2
5119
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 separate foreign keys to two other tables. I have read that it is always a good idea to create indexes on foreign keys. Should I create single indexes on each of these fields? Or is that not necessary since they are already part of a composite...
85
4292
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 offending index are. Why does it force you to determine that information for yourself when it could save you a step and just tell you? This seems like a "no-brainer" to me. Am I missing something?
8
5574
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), but I'm looking to understand what scenario might prompt either setting (yes or no). Any clarity you can provide is much appreciated! Thanks kindly.
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9161
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8897
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6522
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.