Hi,
I have a very simple problem, but do not know an elegant way to
accomplish this.
###
# I have a list of names:
names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
# and another set of names that I want to insert into
# the names list at some indexed locations:
surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
# The thing I couldn't figure out is, after I insert a
# surname the rest of the indices are not valid.
# That is, the following won't work:
for i, x in surnames.iteritems():
names.insert(i,surnames[i])
###
I am searching a nice way to do this. For instance, is there a more
robust way to store indices (as some sort of pointers maybe?)
- Levent 7 1667 le**********@gmail.com schrieb: Hi,
I have a very simple problem, but do not know an elegant way to accomplish this. ### # I have a list of names: names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
# and another set of names that I want to insert into # the names list at some indexed locations: surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
# The thing I couldn't figure out is, after I insert a # surname the rest of the indices are not valid. # That is, the following won't work: for i, x in surnames.iteritems(): names.insert(i,surnames[i]) ###
I am searching a nice way to do this. For instance, is there a more robust way to store indices (as some sort of pointers maybe?)
Use a dictionary for both of them?
The concept of indices is that they IMPLY a position. So either you work
in a way that you e.g. add the surnames in a defined order and adjust
the subsequent indices, or you discard the approach entirely and e.g use
a map of first to surnames.
Diez
En/na le**********@gmail.com ha escrit: Hi,
I have a very simple problem, but do not know an elegant way to accomplish this. ### # I have a list of names: names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
# and another set of names that I want to insert into # the names list at some indexed locations: surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
# The thing I couldn't figure out is, after I insert a # surname the rest of the indices are not valid. # That is, the following won't work: for i, x in surnames.iteritems(): names.insert(i,surnames[i]) ###
In my previous post I've misunderstood the problem. Here is a valid
solution:
keys = surnames.keys()
keys.sort()
count = 0
for i in keys :
names.insert(i + count, surnames[i])
count = count + 1
HTH le**********@gmail.com wrote: # I have a list of names: names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat']
# and another set of names that I want to insert into # the names list at some indexed locations: surnames = { 1: 'kent', 3:'parker', 5:'wayne' }
# The thing I couldn't figure out is, after I insert a # surname the rest of the indices are not valid. # That is, the following won't work: for i, x in surnames.iteritems(): names.insert(i,surnames[i])
This seems to work (tested only with what you see below):: names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] surnames = {1:'kent', 3:'parker', 5:'wayne'} for index in sorted(surnames, reverse=True):
... names.insert(index, surnames[index])
... names
['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce',
'wayne', 'bat']
I just did the inserts from right to left, that is, starting at the end.
That way, after an insert, I don't have to adjust any indices.
You may also find that if you do a lot of inserts into the list, it may
be more efficient to create a new list, e.g.::
names = ['clark', 'super', 'peter', 'spider', 'bruce', 'bat'] surnames = {1:'kent', 3:'parker', 5:'wayne'} new_names = [] for i, name in enumerate(names):
... if i in surnames:
... new_names.append(surnames[i])
... new_names.append(name)
... new_names
['clark', 'kent', 'super', 'peter', 'parker', 'spider', 'bruce',
'wayne', 'bat']
STeVe
Thanks for the answers. Enumerating in reverse is indeed quite a smart
idea.
The fact is though, I overly simplified the task in the super-hero
example. In the real case, the dictionary keys are not necessarily the
indices for inserts; that is to say, the inserts do not necessarily
take place in some sorted order.
I think I was thinking more of a linked-list idea, where you do not
store the indices as integers to some random access array but rather as
pointers into list's nodes. Then the subsequent inserts would not hurt
previously stored pointers. For those who know a bit C++/STL here is a
sketch of the idea:
name_list heros;
heros.push_back("clark");
// ... add the rest
indexed_name_list surnames;
surnames.push_back(
make_pair( find( heros.begin(), heros.end(), "clark"), "kent") )
); // the find function returns an iterator to appropriate location
// ... add the rest
for_each(surnames.begin(), surnames.end(), insert_surnames)
// insert_surnames is a callback that receives a single indexed surname
// at a time and does the job, without affecting outer iterators.
I was wondering how to make indices as *robust* in Python... Any ideas?
PS: following is the compilable code-let of the task in C++
// ================================================== ==
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
typedef string name;
typedef pair<list<name>::iterator, string> indexed_name;
void insert_name( list<name>* into, indexed_name in ) {
into->insert(in.first, in.second);
}
int main() {
using namespace std;
// Define super-heros (fathers ignored)
list<name> heros;
heros.push_back("super");
heros.push_back("clark");
heros.push_back("spider");
heros.push_back("peter");
heros.push_back("bat");
heros.push_back("bruce");
// Assign father names to proper son
list<indexed_name> surnames;
surnames.push_back( // ++ is to have surname inserted _after_ the
name
make_pair(++find(heros.begin(),heros.end(),"clark" ),
string("kent"))
);
surnames.push_back(
make_pair(++find(heros.begin(),heros.end(),"peter" ),
string("parker"))
);
surnames.push_back(
make_pair(++find(heros.begin(),heros.end(),"bruce" ),
string("wayne"))
);
// Insert surnames succeeding appropriate heros
for_each(surnames.begin(), surnames.end(),
bind1st(ptr_fun(insert_name), &heros) );
// Salute the heros
copy(heros.begin(),heros.end(),ostream_iterator<st ring>(cout," "));
cout << endl;
return 0;
}
// ================================================== ===
levent wrote: Thanks for the answers. Enumerating in reverse is indeed quite a smart idea.
The fact is though, I overly simplified the task in the super-hero example. In the real case, the dictionary keys are not necessarily the indices for inserts; that is to say, the inserts do not necessarily take place in some sorted order.
I think I was thinking more of a linked-list idea, where you do not store the indices as integers to some random access array but rather as pointers into list's nodes. Then the subsequent inserts would not hurt previously stored pointers. For those who know a bit C++/STL here is a sketch of the idea:
name_list heros; heros.push_back("clark"); // ... add the rest indexed_name_list surnames; surnames.push_back( make_pair( find( heros.begin(), heros.end(), "clark"), "kent") ) ); // the find function returns an iterator to appropriate location // ... add the rest
for_each(surnames.begin(), surnames.end(), insert_surnames) // insert_surnames is a callback that receives a single indexed surname // at a time and does the job, without affecting outer iterators.
I was wondering how to make indices as *robust* in Python... Any ideas?
Python's list is technically a vector. You can therefore either search for
the insertion point in a timely fashion:
heros = ["super", "clark", "spider", "peter", "bat", "bruce"]
names = [("clark", "kent"), ("peter", "parker"), ("bruce", "wayne")]
for first, last in names:
heros.insert(heros.index(first)+1, last)
print heros
or you have to snatch a real (linked) list from somewhere. Here's an ad-hoc
implementation:
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.right = next
def __str__(self):
return "List(%s)" % ", ".join(repr(n.value) for n in self)
def __iter__(self):
item = self
while item:
yield item
item = item.right
def find(self, value):
for item in self:
if item.value == value:
return item
raise ValueError("%r not found" % (value,))
def insert_after(self, value):
self.right = Node(value, self.right)
@staticmethod
def from_list(items):
items = iter(items)
try:
first = items.next()
except StopIteration:
raise ValueError("empty lists not supported")
cur = head = Node(first)
for value in items:
node = Node(value)
cur.right = node
cur = node
return head
if __name__ == "__main__":
heros = ["super", "clark", "spider", "peter", "bat", "bruce"]
heros = Node.from_list(heros)
names = [("clark", "kent"), ("peter", "parker"), ("bruce", "wayne")]
surnames = [(heros.find(f), s) for f, s in names]
print heros
for node, value in surnames:
node.insert_after(value)
print heros
Peter
In <11**********************@g10g2000cwb.googlegroups .com>, levent wrote: I think I was thinking more of a linked-list idea, where you do not store the indices as integers to some random access array but rather as pointers into list's nodes. Then the subsequent inserts would not hurt previously stored pointers. For those who know a bit C++/STL here is a sketch of the idea:
name_list heros; heros.push_back("clark"); // ... add the rest indexed_name_list surnames; surnames.push_back( make_pair( find( heros.begin(), heros.end(), "clark"), "kent") ) ); // the find function returns an iterator to appropriate location // ... add the rest
for_each(surnames.begin(), surnames.end(), insert_surnames) // insert_surnames is a callback that receives a single indexed surname // at a time and does the job, without affecting outer iterators.
I was wondering how to make indices as *robust* in Python... Any ideas?
What about putting all information for each super hero into an object or
at least a list? And those objects/lists can then be stored into a
dictionary with the first name of the heroes as key. Something like this:
heroes = [['super', 'clark'], ['spider', 'peter'], ['bat', 'bruce']]
name2hero = dict((hero[1], hero) for hero in heroes)
fullnames = [['clark', 'kent'], ['peter', 'parker'], ['bruce', 'wayne']]
for name, surname in fullnames:
name2hero[name].append(surname)
for hero in heroes:
print 'Hello %s a.k.a %s %s' % tuple(hero)
IMHO you shouldn't try to program C++ in Python. Take a step back and
describe *what* you want to achieve and not *how* you do it in another
language. And then implement it in Python.
Ciao,
Marc 'BlackJack' Rintsch
levent wrote: Thanks for the answers. Enumerating in reverse is indeed quite a smart idea.
The fact is though, I overly simplified the task in the super-hero example. In the real case, the dictionary keys are not necessarily the indices for inserts; that is to say, the inserts do not necessarily take place in some sorted order.
I think I was thinking more of a linked-list idea, where you do not store the indices as integers to some random access array but rather as pointers into list's nodes. Then the subsequent inserts would not hurt previously stored pointers. For those who know a bit C++/STL here is a sketch of the idea:
Sorry, I don't know C++/STL, so I don't understand the example you gave.
If your dict doesn't already come with the indices, can't you just
create a dict that does? heros = ["super", "clark", "spider", "peter", "bat", "bruce"] names = dict(clark="kent", peter="parker", bruce="wayne") heros_indices = {} for index, hero_word in enumerate(heros):
.... if hero_word in names:
.... heros_indices[index + 1] = names[hero_word]
.... for index in sorted(heros_indices, reverse=True):
.... heros.insert(index, heros_indices[index])
.... heros
['super', 'clark', 'kent', 'spider', 'peter', 'parker', 'bat', 'bruce',
'wayne']
STeVe This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: mittal.pradeep |
last post by:
What is the better table design for a data collection application.
1. Vertical model (pk, attributeName, AttributeValue)
2. Custom columns (pk, custom1, custom2, custom3...custom50)
Since the...
|
by: maxmarengo |
last post by:
I am trying to write a query in Access (or SQL) that works on a table
like this:
Location Gridreference
Ben Nevis NQ1234512345
Ben Doon NQ1230012300
and so on for several thousand...
|
by: Andy Johns |
last post by:
I've seen plenty of examples of file uploads in ASP.NET when the only
form element is the file input type, but I've not seen a practical
example of a file upload routine running alongside other...
|
by: Altman |
last post by:
I would like to use an indexed property to access my private array of user
controls. If I don't use an indexed property, the property will show up in
my Properties Window during development. Is...
|
by: RyanTaylor |
last post by:
I have a final coming up later this week in my beginning Java class and my
prof has decided to give us possible Javascript code we may have to write.
Problem is, we didn't really cover JS and what...
|
by: Stephene |
last post by:
New to the world of web design/php/mysql and need help please.
What I'm trying to do:
I would like a web page with three drop down menus each populated by a query
The first represents...
|
by: rn5a |
last post by:
A Form has 2 select lists. The 1st one whose size is 5 (meaning 5
options are shown at any given time) allows multiple selection whereas
the 2nd one allows only 1 option to be selected at a time.
...
|
by: David C. Ullrich |
last post by:
Having a hard time phrasing this in the form
of a question...
The other day I saw a thread where someone asked
about overrideable properties and nobody offered
the advice that properties are...
|
by: AmberJain |
last post by:
Windows Autorun FAQs: List of autostart locations
Linked from the Original article- "Windows Autorun FAQs: Description".
Que: Can you list all the autostart locations for windows?
Ans: Here is...
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
| |