473,416 Members | 1,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

append to items depending on prior item

Hi All,

I have tried to come up with a way to do this myself and all I end up with
is very long code.

What I have is a say item1, item4, item2, item1 etc...

What I want to do is append to each item an extra value depending on the
previous item.

from random import *

items = [' item1',' item4',' item2',' item1']

items[0].append choice('1','2','3')
print items

for idx in range(len(items)):
if previous item == ['item1']:
next item.append choice('a','b','c')
if previous item == ['item2']:
next item.append choice('d','e','f')

print items
appended items = item1b, item4a, item2f etc...

Now I know that the code is hopelessly wrong - you can't append a string,
but you get the idea. Doing it using if statements could go on and on. Could
someone show me a short way

Thanks,

M


Jul 18 '05 #1
6 1500
Hi All,

Of course that should be

next Item + (choice('a,b,c'))

Jul 18 '05 #2
M. Clift wrote:
Now I know that the code is hopelessly wrong
[...]
Could someone show me a short way

items = "item1 item4 item2 item1".split()
[i + random.choice(dict(item1="abc", item2="def").get(p, [""])) for (p,

i) in zip(items[-1:]+items[:-1], items)]
['item1c', 'item4c', 'item2', 'item1f']
Peter

Jul 18 '05 #3
M. Clift <no***@here.com> wrote:
...
What I have is a say item1, item4, item2, item1 etc...

What I want to do is append to each item an extra value depending on the
previous item.

from random import *

items = [' item1',' item4',' item2',' item1']

items[0].append choice('1','2','3')
print items

for idx in range(len(items)):
if previous item == ['item1']:
next item.append choice('a','b','c')
if previous item == ['item2']:
next item.append choice('d','e','f')

print items

appended items = item1b, item4a, item2f etc...


This latest example totally contrast with everything else you're saying.
How could 'b' get appended to the first 'item1', for example, when
you're trying to use a choice among '1', '2' and '3'?! I'm going to try
to guess what you mean (if you had been a bit more precise in your
example of desired input and output it WOULD have been far better, of
course)...:

def weird_appender(sequence):
choices = dict({None: '123'}, item1='abc', item2='def')
previous = None
for item in sequence:
yield item+random.choice(choices.get(previous, choices[None]))
previous = item

and if for some super=weird reason you want to trample the contents of
list items rather than just operating on a sequence-in / sequence-out
basis, items[:]=weird_appender(items) will serve.
Alex
Jul 18 '05 #4
Hi Peter,

Thankyou, it looks perfect. At the risk of sounding dumb, however, what do I
print to get your output?

items = "item1 item4 item2 item1".split()
[i + random.choice(dict(item1="abc", item2="def").get(p, [""]))
for (p,i) in zip(items[-1:]+items[:-1], items)]
print ???

Thanks,

M
Jul 18 '05 #5
M. Clift wrote:
Thankyou, it looks perfect. At the risk of sounding dumb, however, what do
I print to get your output?


You would print all the stuff inside [], i. e.

result = [i + random.choice(dict(item1="abc", item2="def").get(p, [""]))
for (p, i) in zip(items[-1:]+items[:-1], items)]
print result

but: the code was *not* meant to be perfect - rather as close as you can get
to obfuscation in Python.
You should first describe exactly what you want in terms of input/output.
Stating a problem precisely is often the hardest and largest part of its
solution. After that try to write a script as _simple_ and _clear_ as you
can (in Python as opposed to your pseudocode).
If you then ask on c.l.py for help with a specific problem you encounter or
for possible improvements, you'll end up with an idiomatic and
understandable solution which is not necessarily the shortest.
In short: short != good.

More practially:
- a plain old for-loop (like in Alex Martelli's post) with a variable to
remember the previous item beats my zip() magic in efficiency and - more
importantly - in clarity.
- if you encounter a long list of if ... elif ... statements, this can often
be simplified into a dictionary lookup.

HTH ...really,
Peter
Jul 18 '05 #6
Hi Peter,

Thankyou. You have been really helpful, I appreciate it.

Malcolm
Jul 18 '05 #7

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

Similar topics

4
by: John Guarnieri | last post by:
Hi All, I need some code to drag items in a list box either up or down along with not just the text but with the itemdata too. Can anyone hook me up? TIA John
0
by: Tom | last post by:
Using AccessXP - Access2000 In my application, when an order is entered, inventory is automatically adjusted, a pull list is created, items are pulled to fill the order, and the order is...
0
by: karinski | last post by:
Hi All, I have a split f/e - b/e setup on my database with RWOP queries on the front end. The code below gets a PO number(s), and vendor name from a multi choice list box on another form. It...
9
by: Alpha | last post by:
Hi, How can I set all the items in a listbox to be selected? I can't find a property or mehtod to do it so I thought I'll try using setselected method but I need to find out how many items are in...
2
by: Samantha Penhale | last post by:
Hi, I have a drop down list ddlServers and in my data access layer I run a stored procedure to populate it. I need to be able to append items to the drop down list and don't know how to do this....
0
by: Elaine | last post by:
I have a truly curious problem with HtmlHelp and Sibling Mode in Visual C++ ..Net 2003 in an MFC app. Sibling mode allows the help viewer to display on top of the app, but if the app is clicked,...
5
by: Kat | last post by:
Hi, I'm trying to set up an asp.net page using flow layout so I'm putting all my controls into a table grid, etc. I use several radiobuttonlists and datagrids that are generated from datasource....
0
by: e | last post by:
My goal is to create a "WindowsXP add/remove programs"-style listbox, where the selected item is bigger (taller) than the others, and displays different content when selected. When the listbox's...
0
by: fahadq | last post by:
Hi I have a program that download files from the email and puts it into the corresponding folder. What i would like to know is how to sort and then appned if the file already exists i.e i get...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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
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
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
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,...

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.