I've got a silly little problem that I'm solving in C++, but I got to
thinking about how much easier it would be in Python. Here's the
problem:
You've got a list of words (actually, they're found by searching a
data structure on the fly, but for now let's assume you've got them as
a list). You need to create a comma-delimited list of these words.
There might be duplicates in the original list, which you want to
eliminate in the final list. You don't care what order they're in,
except that there is a distinguised word which must come first if it
appears at all.
Some examples ("foo" is the distinguised word):
["foo"] => "foo"
["foo", "bar"] => "foo, bar"
["bar", "foo"] => "foo, bar"
["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"
The best I've come up with is the following. Can anybody think of a
simplier way?
--------------------
words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
# Eliminate the duplicates; probably use set() in Python 2.4
d = dict()
for w in words:
d[w] = w
if d.has_key ("foo"):
newWords = ["foo"]
del (d["foo"])
else:
newWords = []
for w in d.keys():
newWords.append (w)
s = ', '.join (newWords)
print s
-------------------- 5 2042 ro*@panix.com (Roy Smith) writes: I've got a silly little problem that I'm solving in C++, but I got to thinking about how much easier it would be in Python. Here's the problem:
You've got a list of words (actually, they're found by searching a data structure on the fly, but for now let's assume you've got them as a list). You need to create a comma-delimited list of these words. There might be duplicates in the original list, which you want to eliminate in the final list. You don't care what order they're in, except that there is a distinguised word which must come first if it appears at all.
Some examples ("foo" is the distinguised word):
["foo"] => "foo" ["foo", "bar"] => "foo, bar" ["bar", "foo"] => "foo, bar" ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"
The best I've come up with is the following. Can anybody think of a simplier way?
....
How about :
..>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
..>>> ', '.join(dict( ( (w,w) for w in words ) ).keys())
'baz, foo, bar'
..>>> words = ["foo",]
..>>> ', '.join(dict( ( (w,w) for w in words ) ).keys())
'foo'
or with Python 2.3 or higher:
..>>> import sets
..>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
..>>> ', '.join(sets.Set (words))
'baz, foo, bar'
..>>> words = ["foo",]
..>>> ', '.join(sets.Set (words))
'foo'
Kind regards
Berthold
-- be******@xn--hllmanns-n4a.de / <http://höllmanns.de/> bh***@web.de / <http://starship.python .net/crew/bhoel/>
Roy Smith wrote: You've got a list of words (actually, they're found by searching a data structure on the fly, but for now let's assume you've got them as a list). You need to create a comma-delimited list of these words. There might be duplicates in the original list, which you want to eliminate in the final list. You don't care what order they're in, except that there is a distinguised word which must come first if it appears at all.
Some examples ("foo" is the distinguised word):
["foo"] => "foo" ["foo", "bar"] => "foo, bar" ["bar", "foo"] => "foo, bar" ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"
The best I've come up with is the following. Can anybody think of a simplier way?
Who knows whether this is "simpler", but it does demonstrate that you
can customize the sort of a list:
#!/usr/bin/env python
def makesorter(firs t):
"""Return a sort function that sorts first to the top."""
def sorter(x, y):
if x == first:
return -1
elif y == first:
return 1
else:
return 0
return sorter
words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
first = 'foo'
sorter = makesorter(firs t)
unique = {}
for word in words:
unique[word] = word
keys = unique.keys()
keys.sort(sorte r)
print ', '.join(keys)
How about (for 2.4 or 2.3 using "from collections import Set as set":
def combine(source, special='foo'):
parts = set(source)
if special in parts:
return ', '.join([special] + list(parts - set([special])))
return ', '.join(parts)
--Scott David Daniels Sc***********@A cm.Org
Roy Smith wrote: The best I've come up with is the following. Can anybody think of a simplier way?
-------------------- words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
# Eliminate the duplicates; probably use set() in Python 2.4 d = dict() for w in words: d[w] = w
if d.has_key ("foo"): newWords = ["foo"] del (d["foo"]) else: newWords = []
for w in d.keys(): newWords.append (w)
s = ', '.join (newWords) print s --------------------
You need to make the dictionary and list types work harder for you. They
have a variety of methods you might find useful. words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] distinguished = ["foo"] d = dict.fromkeys(w ords, True) newwords = [ w for w in distinguished if d.pop(w, False) ] newwords.extend (d.keys()) newwords
['foo', 'baz', 'bar']
On 5 Jan 2005 17:05:40 -0500, ro*@panix.com (Roy Smith) wrote: I've got a silly little problem that I'm solving in C++, but I got to thinking about how much easier it would be in Python. Here's the problem:
You've got a list of words (actually, they're found by searching a data structure on the fly, but for now let's assume you've got them as a list). You need to create a comma-delimited list of these words. There might be duplicates in the original list, which you want to eliminate in the final list. You don't care what order they're in, except that there is a distinguised word which must come first if it appears at all.
Some examples ("foo" is the distinguised word):
["foo"] => "foo" ["foo", "bar"] => "foo, bar" ["bar", "foo"] => "foo, bar" ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar"
The best I've come up with is the following. Can anybody think of a simplier way?
(Not tested beyond what you see ;-)
python 2.4: words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] w2 = list(t[1] for t in sorted((w!='foo ', w) for w in set(words))) w2
['foo', 'bar', 'baz']
Gets you a sort in the bargain ;-)
-------------------- words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"]
# Eliminate the duplicates; probably use set() in Python 2.4
Yup, but 2.3 can be a one-liner too:
words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] w2 = ('foo' in words and ['foo'] or []) + [w for w in dict(zip(words, words)) if w!='foo'] w2
['foo', 'baz', 'bar']
Not sorted, but foo is out front.
d = dict() for w in words: d[w] = w
if d.has_key ("foo"): newWords = ["foo"] del (d["foo"]) else: newWords = []
for w in d.keys(): newWords.append (w)
s = ', '.join (newWords) print s --------------------
Regards,
Bengt Richter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Bennett Haselton |
last post by:
I'm looking for a PHP tutorial that specializes in how to build sites
that are based around user logins. i.e. the user logs in on the front
page, and are taken to a main login page where fields on the page are
populated with values from some server-side database. Ideally, there
would be a server-side "user" database table, with fields such as
"age", so that you could insert a short tag in the PHP source like:
Your age is: <?php ?>
...
|
by: Alberto Vera |
last post by:
Hello:
I have the next structure:
How Can I make it using Python?
How Can I update the value of 6?
|
by: Derek |
last post by:
I came upon the idea of writting a logging class that
uses a Python-ish syntax that's easy on the eyes (IMO):
int x = 1;
double y = 2.5;
std::string z = "result";
debug = "Results:", x, y, z;
The above example outputs:
|
by: Raterus |
last post by:
Hi,
I'm looking for ideas for the most efficient way to accomplish this. I have a string representing names a person goes by.
"John Myers Joe John Myers"
And I need to parse it in such a way that I end up with an array of UNIQUE strings that appear in the original string (In no particular order)
arr(0) = "John"
arr(1) = "Myers"
|
by: frizzle |
last post by:
Hi groupies
I'm building a news site, to wich a user can add new items into a mySQL
db.
It's still in testfase, but it's so extremely slow, i want to figure
out what i'm doing wrong, or what to change before it goes live ...
I know it's quite a long story, but i would be so happy if anyone could
help me out here ...
I've read on optimizing DB structure etc, but still cannot speed things
up ...
| |
by: ILCSP |
last post by:
Hi, I have a sql table containing the answers for some tests. The
information in this table is presented vertically and I need to create
strings with them. I know how to read the data in VB.Net and use a
StreamWriter to build the strings. However, the problem lies with the
reading of each row.
Most of the test takers don't give answers to ALL of the items in a
test, but those unanswered items need to be accounted for by using a
comma...
|
by: Steve Richter |
last post by:
KeyValuePair<string,stringhas a ToString method that returns the
KeyValue pair seperated by a comma and enclosed in :
Is this method used as a building block for serialization?
The reason I ask is because I dont see a "FromString" or "Parse"
static method that takes a string as an argument and returns a
KeyValuePair<string,stringobject.
|
by: Lighter |
last post by:
In 5.3.3.4 of the standard, the standard provides that "The lvalue-to-
rvalue(4.1), array-to-pointer(4.2),and function-to-pointer(4.3)
standard conversions are not applied to the operand of sizeof."
I think this rule is easy to understand. Because I can find the
contexts of applying the rule as follows.
(1)
int* p = 0;
int b1 = sizeof(*p); // OK, b1 = 4, *p would not be evaluated.
|
by: Twanne |
last post by:
I've got this query
Set rst4 = db.OpenRecordset("SELECT L,M,S FROM referenties WHERE type = '" & Form_PatChoise.ctype & "' AND geslacht = '" & Form_PatChoise.Sex & "' AND leeftijd = '" & checkage & "';")
when I remove the single quotes I get an error about a comma to much.
When I let them there I get a datatype missmatch. I can't change the field to text because I use the field to calculate some other values.
I know this...
|
by: yaaara |
last post by:
Hello,
I hope someone can help me in resolving the following in access 2003:
I have a table with the following fields:
emp_id,emp_name,repdate,actions,duration,lob,category,ltstatus
emp_id is not unique and there appears to be no primary key for this table.
|
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...
| |
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...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |