473,624 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace one element of a tuple

I have an array(?) (sorry, I'm new* to python so I'm probably mangling
the terminology) that looks like this:

[((1028L, datetime.dateti me(2006, 5, 30, 7, 0), datetime.dateti me(2006,
5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the
Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects
a snowball.', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L,
'Default', 9L, 'SH044107', 'EP0441070123', datetime.dateti me(2006, 5,
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2 002, 11, 28), 0, 0L,
0),), ((1028L, datetime.dateti me(2006, 5, 4, 10, 0),
datetime.dateti me(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues',
'', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default',
6L, 'SH326087', 'EP3260870141', datetime.dateti me(2006, 5, 4, 10, 31,
30), 1163673536L, 0.0, 1, datetime.date(2 005, 3, 19), 0, 0L, 0),)]

I want to replace every instance of 'tooth.seiner.l an' with 'localhost'.
There may be lots and lots of these entries (they're pulled from my
mythtv database).

I could brute-force this by rewriting the whole thing and replacing
every 9th element but there has to be a better way....

I've looked at various search-and-replace snippets but none that address
what I am trying to do....

--Yan

*I'm not really new to python, just very very rusty. Last time I used
it was about 3 years ago, and I was equally clueless....
Jun 1 '06 #1
8 5919

Captain Dondo wrote:
I have an array(?) (sorry, I'm new* to python so I'm probably mangling
the terminology) that looks like this:

[((1028L, datetime.dateti me(2006, 5, 30, 7, 0), datetime.dateti me(2006,
5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the
Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects
a snowball.', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L,
'Default', 9L, 'SH044107', 'EP0441070123', datetime.dateti me(2006, 5,
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2 002, 11, 28), 0, 0L,
0),), ((1028L, datetime.dateti me(2006, 5, 4, 10, 0),
datetime.dateti me(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues',
'', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default',
6L, 'SH326087', 'EP3260870141', datetime.dateti me(2006, 5, 4, 10, 31,
30), 1163673536L, 0.0, 1, datetime.date(2 005, 3, 19), 0, 0L, 0),)]

I want to replace every instance of 'tooth.seiner.l an' with 'localhost'.
There may be lots and lots of these entries (they're pulled from my
mythtv database).

I could brute-force this by rewriting the whole thing and replacing
every 9th element but there has to be a better way....

I've looked at various search-and-replace snippets but none that address
what I am trying to do....

--Yan

*I'm not really new to python, just very very rusty. Last time I used
it was about 3 years ago, and I was equally clueless....

There's a lot of parenthesis :) not easy to read, but unless I'm
seeing something odd, you have string literals in a tuple. So I don't
think your going to find a better way than brute force recreation.

FYI lists are between [] and are mutable
Tuples are between () and are immutable. If I'm countin paren's right
you have a list that contains a tuple, that contains another tuple with
1 element in it.

so you can recreate the tuples... or convert the whole thing to a list
of lists.

Jun 1 '06 #2
>> I've looked at various search-and-replace snippets but none that address
what I am trying to do....


I think you need to tell more about what you're trying to do. You say
it's in a database? Is that why you can't just put the whole blob in
your text editor and do search-and-replace?

And is that also why you can't turn it into a giant string and do
giantstring.rep lace('unwanted' ,'wanted')

rd

Jun 1 '06 #3
BartlebyScriven er wrote:
I've looked at various search-and-replace snippets but none that address
what I am trying to do....

I think you need to tell more about what you're trying to do. You say
it's in a database? Is that why you can't just put the whole blob in
your text editor and do search-and-replace?

And is that also why you can't turn it into a giant string and do
giantstring.rep lace('unwanted' ,'wanted')

rd


Fair enough. I am trying to pull records from one database (on
tooth.seiner.la n) and create a smaller table with only selected elements
in another database (on localhost aka hermes).

My code so far:

import MySQLdb
import sys, os, os.path, time, string, dialog

masterBackend=" tooth.seiner.la n"
toGoBackend="he rmes.seiner.lan "

masterDB=MySQLd b.connect(host= masterBackend,u ser="mythtv",pa sswd="mythtv",d b="mythconverg" )

# pull recordings from masterDB

c=masterDB.curs or()
c.execute("""SE LECT title, subtitle, starttime FROM recorded""")

# build our dialog checkbox

d = dialog.Dialog(d ialog="dialog")
d.add_persisten t_args(["--backtitle", "Myth2Go"])

recordings=[]
for listing in c.fetchall():
recordings.appe nd(
(listing[0]+'|'+listing[2].isoformat(),
listing[1],0))

recordings.sort ()

(retcode, itemlist) = d.checklist(tex t="",
height=15, width=70, list_height=7,
choices=recordi ngs,
title="Which recordings do you want to transfer?")

selectlist=[]
for listing in itemlist:
print listing
(rectitle, recdate) = listing.split(' |',1)
c.execute("""SE LECT * FROM recorded WHERE title=%s AND
starttime=%s""" ,(rectitle,recd ate))
selectlist.appe nd(c.fetchone() )

=============== =============== =============== ===========

The problem is the last line. I am creating a bunch of tuples that are,
for my purposes, incorrect. I would like to create them with
masterBackend replaced by toGoBackend.

Currently (I corrected a small bug based on another post) after a user
selects what recordings s/he wants, selectlist contains:

[

(1028L, datetime.dateti me(2006, 5, 26, 7, 0), datetime.dateti me(2006, 5,
26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '',
'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default', 9L,
'SH044107', 'EP0441070207', datetime.dateti me(2006, 5, 26, 7, 31, 1),
1162899392L, 0.0, 0, datetime.date(2 006, 5, 26), 0, 0L, 0),

(1028L, datetime.dateti me(2006, 5, 27, 9, 0), datetime.dateti me(2006, 5,
27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children',
'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107',
'EP0441070204', datetime.dateti me(2006, 5, 27, 9, 31, 26), 1164783552L,
0.0, 0, datetime.date(2 006, 5, 23), 0, 0L, 0),

(1028L, datetime.dateti me(2006, 5, 30, 7, 0), datetime.dateti me(2006, 5,
30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball',
'Prunella prepares for a sleepover with Marina; D.W. protects a
snowball.', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L,
'Default', 9L, 'SH044107', 'EP0441070123', datetime.dateti me(2006, 5,
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2 002, 11, 28), 0, 0L, 0)

]

which is the correct format to insert into the new database.

What I'd like to do is build the correct selectlist in the first place,
rather than build the wrong one and then rebuild a correct one.

I can't find a replace method that would work on a tuple (not surprising
since they're immutable) but I also can't find a replace function that
would replace an element of a tuple and return a new tuple.

--Yan
Jun 1 '06 #4
Captain Dondo wrote:
What I'd like to do is build the correct selectlist in the first place,
rather than build the wrong one and then rebuild a correct one.


This is sounding more like a SQL/DB problem and less like a Python one.
If you have a field that is being pulled from the database that you
would like to do a substitution on, I'm fairly sure MySQL includes a
CASE statement in their flavor of SQL. Instead of performing a SELECT
* in your script you could select the individual fields you want, and
instead of just pulling the problematic column as is, you could pull it
as something like "select case when sourcehost = x then y else
sourcehost end case, ...". Naturally if an entire column needs to be
replaced with a static value, you won't even need to use CASE.

HTH

Jun 1 '06 #5
Brian wrote:
Captain Dondo wrote:
What I'd like to do is build the correct selectlist in the first place,
rather than build the wrong one and then rebuild a correct one.

This is sounding more like a SQL/DB problem and less like a Python one.
If you have a field that is being pulled from the database that you
would like to do a substitution on, I'm fairly sure MySQL includes a
CASE statement in their flavor of SQL. Instead of performing a SELECT
* in your script you could select the individual fields you want, and
instead of just pulling the problematic column as is, you could pull it
as something like "select case when sourcehost = x then y else
sourcehost end case, ...". Naturally if an entire column needs to be
replaced with a static value, you won't even need to use CASE.


AFAICT, that one column is always the same, the name of the host that
the database resides on. As myth can use multiple backends , it sort of
makes sense, but it seems redunandant to me. Even with mutliple
backends, I would hope you have a single database....

I thought about just picking all the other fields via the SQL query, but
this seemed simpler to me....

Anyway, here's the code I came up with:

for listing in itemlist:
(rectitle, recdate) = listing.split(' |',1)
c.execute("""SE LECT * FROM recorded WHERE title=%s AND
starttime=%s""" ,(rectitle,recd ate))
for listitem in c.fetchall():
if 'tooth.seiner.l an' in listitem:
selectlist.appe nd(listitem[:7] +
('hermes.seiner .lan',) + listitem[9:])
else:
selectlist.appe nd(listitem)
Jun 1 '06 #6
>> that one column is always the same, the name of the host that
the database resides on.


Then why are you pulling all of the other stuff out of the db? Why
don't you just

UPDATE tablename
SET hostname(or colname) = 'localhost'
WHERE search condition = the rows you want to change

Jun 1 '06 #7
BartlebyScriven er wrote:
that one column is always the same, the name of the host that
the database resides on.

Then why are you pulling all of the other stuff out of the db? Why
don't you just

UPDATE tablename
SET hostname(or colname) = 'localhost'
WHERE search condition = the rows you want to change


Well, there is an interactive dialog where the user picks which records
s/he wants to put into the other database. So in the target database,
that table may not even exist until the user selects which records go in
there.

But it does sound like I need to do some work on the database query.... :-)

--Yan
Jun 1 '06 #8
Captain Dondo a écrit :
(snip)
c=masterDB.curs or()
c.execute("""SE LECT title, subtitle, starttime FROM recorded""")

# build our dialog checkbox

d = dialog.Dialog(d ialog="dialog")
d.add_persisten t_args(["--backtitle", "Myth2Go"])

recordings=[]
for listing in c.fetchall():
recordings.appe nd(
(listing[0]+'|'+listing[2].isoformat(),
listing[1],0))

recordings.sort ()
Why don't you just add an order by clause in your sql statement ???
(retcode, itemlist) = d.checklist(tex t="",
height=15, width=70, list_height=7,
choices=recordi ngs,
title="Which recordings do you want to transfer?")

selectlist=[]
for listing in itemlist:
print listing
(rectitle, recdate) = listing.split(' |',1)
c.execute("""SE LECT * FROM recorded WHERE title=%s AND
starttime=%s""" ,(rectitle,recd ate))
is the combination of title and starttime a unique key ?

Also, unless you have lots of records with huge blobs in 'recorded'
table, this smells like a WTF.
selectlist.appe nd(c.fetchone() )
The problem is the last line.
I'm afraid this is not the only problem...
I am creating a bunch of tuples that are,
for my purposes, incorrect.
selectlist.appe nd(list(c.fetch one)) would create a bunch of lists instead.
I would like to create them with
masterBackend replaced by toGoBackend.

Currently (I corrected a small bug based on another post) after a user
selects what recordings s/he wants, selectlist contains:

[

(1028L, datetime.dateti me(2006, 5, 26, 7, 0), datetime.dateti me(2006, 5,
26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '',
'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default', 9L,
'SH044107', 'EP0441070207', datetime.dateti me(2006, 5, 26, 7, 31, 1),
1162899392L, 0.0, 0, datetime.date(2 006, 5, 26), 0, 0L, 0),
No huge blob in sight. And since the list of records fits on a dialog
with checkboxes, I think you could easily avoid querying the DB that
many times. FWIW, you could probably query it once only.
(1028L, datetime.dateti me(2006, 5, 27, 9, 0), datetime.dateti me(2006, 5,
27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children',
'tooth.seiner.l an', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107',
'EP0441070204', datetime.dateti me(2006, 5, 27, 9, 31, 26), 1164783552L,
0.0, 0, datetime.date(2 006, 5, 23), 0, 0L, 0),

(1028L, datetime.dateti me(2006, 5, 30, 7, 0), datetime.dateti me(2006, 5,
30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball',
'Prunella prepares for a sleepover with Marina; D.W. protects a
snowball.', 'Children', 'tooth.seiner.l an', None, 0L, None, 1L, 1L,
'Default', 9L, 'SH044107', 'EP0441070123', datetime.dateti me(2006, 5,
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2 002, 11, 28), 0, 0L, 0)

]

which is the correct format to insert into the new database.

What I'd like to do is build the correct selectlist in the first place,
rather than build the wrong one and then rebuild a correct one.

I can't find a replace method that would work on a tuple (not surprising
since they're immutable) but I also can't find a replace function that
would replace an element of a tuple and return a new tuple.


You can of course turn a tuple into a list, then modify the list. But it
would still be a waste of time. Learning the full syntax for a SQL
select might be more useful. You can do something like:

select item1, item2, 'someconstant', item3, ..., from sometable (...)

which avoid having anything to replace.
Assuming that title + starttime is the primary key, and - not knowing
the structure of your table - assuming that starttime is the second
field, title the 5th and subtitle the 6th :

# ---------------------
sql = """
SELECT f1, starttime, f3, f4, title, subtitle, f7, '%s', f9,
(..etc...), f24
FROM recorded
ORDER BY title, starttime
""" % toGoBackend

c.execute(sql)
rows = c.fetchall()
# seems like dialog.checklis t wants strings as tags
# tried with ints, but it crashed...
choices = [(str(i), row[5], 0) for row in rows]
d = dialog.Dialog(d ialog="dialog")
d.add_persisten t_args(["--backtitle", "Myth2Go"])
retcode, indices = d.checklist('', choices=choices )
if retcode:
# exit or return

selectlist = [rows[i] for i in map(int, indices)]
# ---------------------

HTH
Jun 2 '06 #9

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

Similar topics

0
1369
by: Ron Griswold | last post by:
Can anyone tell me why the following will cause the returned tuple elements to remain un collected when the tuple goes out of scope: PyObject * iobj = PyObject_New( PyIntObject, &PyInt_Type ); iobj->ob_ival = val; PyTuple_SetItem( tuple, index, iobj ); return tuple; while the following will collect the elements: PyTuple_SetItem( tuple, index PyInt_FromLong( val ) );
3
4764
by: Miguel J. Jiménez | last post by:
Hi, I have the following node: <node> Some text here with lots of inside it... </node> and I would like it to transfrom it using XSLT to the following: Some text<br/> here with</br> lots of</br> inside it... Being <br/> HTML tags and not simple text like &lt;br/&gt;
22
1884
by: David Isaac | last post by:
Newbie question: I have been generally open to the proposal that list comprehensions should replace 'map', but I ran into a need for something like map(None,x,y) when len(x)>len(y). I cannot it seems use 'zip' because I'll lose info from x. How do I do this as a list comprehension? (Or, more generally, what is the best way to do this without 'map'?) Thanks,
5
12048
by: ma740988 | last post by:
For starters, Happy New Year to all!! I created a vector of pairs where pair first is a primitive and pair second is a vector of ints. So now: # include <iostream> # include <vector>
10
13951
by: localpricemaps | last post by:
i have some html that looks like this <address style="color:#">34 main,<br> Boston, MA</address> and i am trying to use the replace function to get rid of the <Br> that i scrape out using this code: for oText in incident.fetchText( oRE): strTitle += oText.strip()
2
11316
by: nico | last post by:
The following example returns a string type, but I need a tuple... <type 'str'> I need that for a method parameter. Thx
11
1379
by: rh0dium | last post by:
Hi all, I have a simple list to which I want to append another tuple if element 0 is not found anywhere in the list. element = ('/smsc/chp/aztec/padlib/5VT.Cat', '/smsc/chp/aztec/padlib', '5VT.Cat', (33060)) element1 = ('/smsc/chp/aztec/padlib/5VT.Cat2',
4
1637
by: wxPythoner | last post by:
To create a tuple with one element, you need to do this: <type 'tuple'> But if you do this <type 'int'> you don't get a tuple. I thought that just putting a value inside ( )
10
1509
by: TP | last post by:
Hi everybody, I have a question about the difference of behavior of "len" when applied on tuples or on lists. I mean: $ len( ( 'foo', 'bar' ) ) 2 $ len( ( 'foo' ) ) 3 $ len( )
0
8172
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8677
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
8335
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,...
1
6110
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
5563
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();...
0
4079
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
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2605
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 we have to send another system
2
1482
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.