473,513 Members | 2,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on lists

My question is about lists:

Is there a way to remove duplicate items from a list that are
next to each other?

Example...

Performing the operation on ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']
will return ['a', 'b', 'c', 'd', 'e']

Performing the operation on ['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']
will return ['a', 'b', 'c', 'd', 'c', 'd', 'e']

I'm guessing there is probably nothing internal that will do it, so
I may have to write something on my own - just thought I'd check
first ;)

Thanks!

--
Kristofer Pettijohn
kr*******@cybernetik.net
Jul 18 '05 #1
10 1338
On Wed, Jul 28, 2004 at 03:26:54AM +0000, Kristofer Pettijohn wrote:
My question is about lists:

Is there a way to remove duplicate items from a list that are
next to each other?

Example...

Performing the operation on ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']
will return ['a', 'b', 'c', 'd', 'e']

Performing the operation on ['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']
will return ['a', 'b', 'c', 'd', 'c', 'd', 'e']

I'm guessing there is probably nothing internal that will do it, so
I may have to write something on my own - just thought I'd check
first ;)


Nothing builtin that I know of, but it's trivial to write:

def uniq(iterable):
"""Remove consecutive duplicates from a sequence."""

prev = object()
for element in iterable:
if element != prev:
prev = element
yield element
list(uniq(['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e'])) ['a', 'b', 'c', 'd', 'e'] list(uniq(['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']))

['a', 'b', 'c', 'd', 'c', 'd', 'e']

-Andrew.

Jul 18 '05 #2
Am Mittwoch, 28. Juli 2004 05:26 schrieb Kristofer Pettijohn:
My question is about lists:

Is there a way to remove duplicate items from a list that are
next to each other?


They don't even have to be next to each other:

(>= Python 2.3 required)
import sets
list(sets.Set(['a','a','b','b','d','b','c','a','ladida']))

['a', 'c', 'b', 'd', 'ladida']

This doesn't maintain the order of the items, though. If you need that, and
you're sure your list is always sorted, use the example Andrew gave.

Heiko.
Jul 18 '05 #3
Andrew Bennetts <an***************@puzzling.org> wrote:
Nothing builtin that I know of, but it's trivial to write:

def uniq(iterable):
"""Remove consecutive duplicates from a sequence."""

prev = object()
for element in iterable:
if element != prev:
prev = element
yield element


Thank you! Easier than I thought. I don't know why I make things
so hard on myself.

--
Kristofer Pettijohn
kr*******@cybernetik.net
Jul 18 '05 #4
Heiko Wundram <he*****@ceosg.de> wrote:
import sets
list(sets.Set(['a','a','b','b','d','b','c','a','ladida']))

['a', 'c', 'b', 'd', 'ladida']

This doesn't maintain the order of the items, though. If you need that, and
you're sure your list is always sorted, use the example Andrew gave.


Good to know for the future; unfortunately these needed to remain
in order - I'm graphing routes and paths, and if the same node shows
up 2+ times in a row, I needed them weeded out.

Thanks!

--
Kristofer Pettijohn
kr*******@cybernetik.net
Jul 18 '05 #5
Andrew Bennetts wrote:
Nothing builtin that I know of, but it's trivial to write:


Using 2.4, looks like the logic is in itertools.groupby:
from itertools import groupby
l = ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']
list(x for x, _ in itertools.groupby(l))

['a', 'b', 'c', 'd', 'e']

--
Ciao,
Matteo
Jul 18 '05 #6
If x is the given sequence, then
[x[i] for i in filter(lambda i: i==0 or x[i-1]<>x[i], range(len(x)))]
is what you want.

"Kristofer Pettijohn" <kr*******@cybernetik.net> wrote in message
news:41***********************@newsreader.cybernet ik.net...
| My question is about lists:
|
| Is there a way to remove duplicate items from a list that are
| next to each other?
|
| Example...
|
| Performing the operation on ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']
| will return ['a', 'b', 'c', 'd', 'e']
|
| Performing the operation on ['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']
| will return ['a', 'b', 'c', 'd', 'c', 'd', 'e']
|
| I'm guessing there is probably nothing internal that will do it, so
| I may have to write something on my own - just thought I'd check
| first ;)
|
| Thanks!
|
| --
| Kristofer Pettijohn
| kr*******@cybernetik.net
Jul 18 '05 #7
In article <VaKNc.126557$od7.8959@pd7tw3no>,
Elaine Jackson <el***************@home.com> wrote:

If x is the given sequence, then
[x[i] for i in filter(lambda i: i==0 or x[i-1]<>x[i], range(len(x)))]
is what you want.


Please report to the UnPythonic Activities Committee. ;-)
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"To me vi is Zen. To use vi is to practice zen. Every command is a
koan. Profound to the user, unintelligible to the uninitiated. You
discover truth everytime you use it." --*****@lion.austin.ibm.com
Jul 18 '05 #8
"Heiko Wundram" <he*****@ceosg.de> wrote in message
news:ma*************************************@pytho n.org...
import sets
list(sets.Set(['a','a','b','b','d','b','c','a','ladida']))

['a', 'c', 'b', 'd', 'ladida']

Newbie question:
OK, this is great. But I was not aware of this module,
and I was working in my own sets.py.
So how do I handle this namespace issue?
I.e., how can I 'import sets' and get the Python module,
when my own script is named sets.py?

Thanks,
Alan Isaac

Jul 18 '05 #9
On Thu, 29 Jul 2004, Alan G Isaac wrote:
Newbie question:
OK, this is great. But I was not aware of this module,
and I was working in my own sets.py.
So how do I handle this namespace issue?
I.e., how can I 'import sets' and get the Python module,
when my own script is named sets.py?


The best way, of course, is to rename your script ;) it's never a good
idea to give a script the same name as that of a module you plan to use.

If you absolutely must leave your script named sets.py, you can use the
following trick to get to Python's sets.py:

import sys
sys.path.remove('')
import sets

This removes the current directory from Python's search path. Note you
won't be able to access any modules in the current directory after that
line, unless you do a "sys.path.insert(0,'')" first.

Jul 18 '05 #10
Aahz <aa**@pythoncraft.com> wrote:
Elaine Jackson <el***************@home.com> wrote:

If x is the given sequence, then
[x[i] for i in filter(lambda i: i==0 or x[i-1]<>x[i], range(len(x)))]
is what you want.
Please report to the UnPythonic Activities Committee. ;-)
Has the committee considered the other functional solution?
def dedupe(lst, x): .... if not lst or lst[-1] != x:
.... lst.append(x)
.... return lst
.... reduce(dedupe, l, []) ['a', 'b', 'c', 'd', 'e']

If it would help, I'm sure we could get an obfuscation expert to make
it into one line, but without a first-class conditional expression,
it's nothing but a circus trick. Perl envy, like.

Oh, okay, twist my arm...
reduce(lambda r,x: (not r or r[-1]!=x) and r.append(x) or r, l, [])

['a', 'b', 'c', 'd', 'e']

I knew reduce would come in handy for something.
"To me vi is Zen. To use vi is to practice zen. Every command is a
koan. Profound to the user, unintelligible to the uninitiated. You
discover truth everytime you use it." --*****@lion.austin.ibm.com


Apparently vi also shares with koans the characteristic of battering
down the walls of rationality. :-)

--
Although we may never know with complete certainty the identity
of the winner of this year's presidential election, the identity
of the loser is perfectly clear. It is the nation's confidence
in the judge as an impartial guardian of the law.
- Justice John Paul Stevens, from his dissenting opinion Dec 12, 2000
Jul 18 '05 #11

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

Similar topics

2
3703
by: Sean Berry | last post by:
I have two lists... one like the following, list1 ... and the other like this, list2 ... , ] Both lists are much more extensive, the first being a list of about 10 strings, and the...
9
3734
by: Dave H | last post by:
Hello, I have a query regarding definition lists. Is it good practice semantically to use the dt and dd elements to mark up questions and answers in a frequently asked questions list, or FAQ? ...
19
17332
by: CMAR | last post by:
I have the following markup. The problem is that the browser, e.g., IE6, inserts several lines of blank space between the <div> and the following table. Is there a way to minimize that vertical...
22
2073
by: Nunaya | last post by:
We have developed two objects called "customer" and "salesrep". For simplicity, assume that these two objects will talk directly to a database. The database has three tables: customers,...
5
1246
by: Roger Bonine | last post by:
I'm working on a rewrite of our employee database. I plan to implement a fairly heavyweight base class, which includes 20 or 30 fields, including address and phone number collections and the like....
10
1832
by: JustSomeGuy | last post by:
I have a few classes... class a : std::list<baseclass> { int keya; }; class b : std::list<a> { int keyb;
22
10727
by: craig | last post by:
I've declared the following as a "vector" of "lists" using STL vector< list<Edge*> > I've tried many ways to add objects to this but can't figure out how to do it. Does anyone have any tips,...
5
2271
by: bruce | last post by:
hi... i'm trying to deal with multi-dimension lists/arrays i'd like to define a multi-dimension string list, and then manipulate the list as i need... primarily to add lists/information to the...
90
3365
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
5
1197
by: Scott | last post by:
I'm sorry if most of my question's seem "petty", but as I've said before, I need to know the petty just because I need to know. This question is more along the lines of just having you guys...
0
7166
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
7386
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
7543
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...
1
7106
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...
0
3236
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...
0
3226
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1601
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
805
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
459
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...

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.