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 6 1514
Hi All,
Of course that should be
next Item + (choice('a,b,c' ))
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(d ict(item1="abc" , item2="def").ge t(p, [""])) for (p,
i) in zip(items[-1:]+items[:-1], items)]
['item1c', 'item4c', 'item2', 'item1f']
Peter
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.cho ice(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
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(d ict(item1="abc" , item2="def").ge t(p, [""]))
for (p,i) in zip(items[-1:]+items[:-1], items)]
print ???
Thanks,
M
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(d ict(item1="abc" , item2="def").ge t(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
Hi Peter,
Thankyou. You have been really helpful, I appreciate it.
Malcolm This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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 packaged for shippment. The order is then held pending payment and
finally shipped when payment is received. Sometimes prior to shipment the
customer calls and wants to change one or more items, wants to change the
quantity of one or more items or wants...
|
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 then assigns these values,
plus a new receiving number, to the current form. The SQL string is an
append query that copies select fields from the PO line items table
into the receiving line items table and appends the current receiving
number to...
|
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 the listbox.
Thanks,
Alpha
|
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. Here is the code I use to bind
the data retrieved from the DAL to the field.
{
DAL GetAllServers = new DAL();
DataSet dsServerNames = GetAllServers.GetAllServers();
ddlServers.DataSource = dsServerNames;
ddlServers.DataTextField = "Server_Name";
| |
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, then the app becomes the top most window. The idea is to
let the user switch back and forth between the help viewer and the
application.
For the case of Menu Items only, sibling mode does not appear to work
correctly under normal running...
|
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. The
radiobuttonlists are fine, they size depending on how many item are
called into it.
However, the datagrids, prior to filling with data contain FIVE
"Databound" items and the grid does not shrink if it is filled with
only 2 for example....
|
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 DrawMode property is set to OwnerDrawVariable (which mine
is, from design time), the MSDN docs tell me that the MeasureItem event will
be called prior to the DrawItem event, so that the item can be properly
sized before it is drawn to the...
|
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 strString = "9301ARUP" . I'm checking for arup
if strString.instr("ARUP")> 0
if strString.checkfileexist("true") then
add a letter to the end
then save the file to a folder
else
then save the file to a folder
|
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: 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,...
| |
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: 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: 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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |