I need to repeat each item in a list n times, like this function does:
def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitio ns):
newlist.append( item)
return newlist
Output: repeatitems(['a', 'b', 'c'], 3)
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
Clear and simple. But i wonder if there is a more idiomatic way. Surely not this:
def repeatitems(seq uence, repetitions):
return reduce(lambda l, i: l + i, [[item] * repetitions for item in sequence])
? 12 8110
alr wrote: I need to repeat each item in a list n times, like this function does:
def repeatitems(seq uence, repetitions): newlist = [] for item in sequence: for i in range(repetitio ns): newlist.append( item) return newlist
I would make just a minor change:
def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
newlist += repetitions*[item]
return newlist
regards Max M an***@wmdata.co m (alr) wrote in
news:f5******** *************** **@posting.goog le.com: I need to repeat each item in a list n times, like this function does:
def repeatitems(seq uence, repetitions): newlist = [] for item in sequence: for i in range(repetitio ns): newlist.append( item) return newlist
Output:
>>> repeatitems(['a', 'b', 'c'], 3)
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
Clear and simple. But i wonder if there is a more idiomatic way.
The most obvious one that springs to mind is just a slight simplification
of your version:
def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
alr wrote: I need to repeat each item in a list n times, like this function does:
def repeatitems(seq uence, repetitions): newlist = [] for item in sequence: for i in range(repetitio ns): newlist.append( item) return newlist
.... But i wonder if there is a more idiomatic way.
How about this?
def repeatItems(seq uence, repetitions):
return [[item]*repetitions for item in sequence]
"Peter Otten" <__*******@web. de> wrote in message news:bd******** *****@news.t-online.com... How about this?
def repeatItems(seq uence, repetitions): return [[item]*repetitions for item in sequence]
Unfortunately that is equivalent to:
def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
newlist.append([item] * repetitions)
return newlist
and not:
def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
Duncan Booth <du****@NOSPAMr cp.co.uk> wrote in
news:Xn******** *************** ****@127.0.0.1: The most obvious one that springs to mind is just a slight simplification of your version:
def repeatitems(seq uence, repetitions): newlist = [] for item in sequence: newlist.extend([item] * repetitions) return newlist
Or, if you are in a "I've got a new toy to play with" mood you could use
itertools from Python 2.3 to obfuscate it somewhat:
from itertools import chain, izip, repeat
def repeatiterate(s equence, repetitions):
return chain(*izip(*re peat(sequence, repetitions)))
This version returns an iterator, so you might want to throw in a call to
'list' if you want to do anything other than iterating over the result.
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Richard Brodie wrote: Unfortunately that is equivalent to:
def repeatitems(seq uence, repetitions): newlist = [] for item in sequence: newlist.append([item] * repetitions) return newlist
.... but it looked so good. I should have tested it, though.
Je suis desole :-(
"alr" <an***@wmdata.c om> wrote in message
news:f5******** *************** **@posting.goog le.com... I need to repeat each item in a list n times, like this function
does:
Is this really the right question? Any code that requires such an
n-repeat list *could* be rewritten (if you own it) to use the replist
in condensed form: (items, n). If this is not possible, one could
also define a replist class with a __getitem__(sel f, index) that
divides index by self.n and an __iter__() that returns an appropriate
generator.
Terry J. Reedy
>>>>> "alr" == alr <an***@wmdata.c om> writes:
alr> reduce(lambda l, i: l + i, [[item] * repetitions for item in
This doesn't look too bad to me, but perhaps list comprehensions are
clearer?
seq = ['a', 'b', 'c']
print [x for x in seq for x in seq]
>>>>> "alr" == alr <an***@wmdata.c om> writes:
alr> reduce(lambda l, i: l + i, [[item] * repetitions for item in
alr> sequence])
Oops, premature hit of send key. What I meant to say was
seq = ['a', 'b', 'c']
print [x for x in seq for i in range(len(seq))]
JDH This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Charlotte Henkle |
last post by:
Hello;
I'm pondering how to count the number of times an item appears in
total in a nested list. For example:
myList=,,]
I'd like to know that a appeared three times, and b appeared twice,
and the rest appeard only once.
|
by: M. Clift |
last post by:
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.
|
by: Neil Waldie |
last post by:
I am trying to code a class for use with the XMLSerializer that can produce
XML valid for the following schema (fragment):
<xs:element name="Group">
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<xs:element name="SubElement1" />
<xs:element minOccurs="0" maxOccurs="1" name="SubElement2" />
<xs:element minOccurs="0" maxOccurs="1" name="SubElement3" />
</xs:sequence>
|
by: nickheppleston |
last post by:
I'm trying to iterate through repeating elements to extract data using
libxml2 but I'm having zero luck - any help would be appreciated.
My XML source is similar to the following - I'm trying to extract the
line number and product code from the repeating line elements:
<order xmlns="some-ns">
<header>
<orderno>123456</orderno>
</header>
|
by: MCM |
last post by:
I'm working on a plotting control. The plotting control will have a context
menu with basic commands for "scaling", "zooming", etc. Is there a way
that, from the parent form, I can add more commands to the control's context
menu?
I'm envisioning a case where the control has a set of context menu items,
and the parent form also has a set of context menu items.
Thanks.
| |
by: lifity |
last post by:
hi, i am stuck on part of my project and very new to VB.
i had cut my picture into 6 equals part
but need to display them randomly, without repeating the same part of the pic again, in random sequence.
eg, pic1,pic2,pic3,pic4,pic5,pic6 to ==> pic3,pic2,pic6,pic1,pic5,pic4
below are part of my code
Dim theImage(0 To 7) As Object
Dim myArray(0 To 7) As Object
|
by: Gammazoni |
last post by:
Hello, I have a code like that, which has been using by me, but now I need another one, which won't differ a lot, I hope. Please, analize it, I believe that here I'll find somebody with large luggage of experience. Please, write any suggestions you have.
Sub test()
Dim ws As Worksheet, a, i As Long, ii As Long, b(), n As Long, w(), e
With CreateObject("Scripting.Dictionary")
For Each ws In Worksheets
With...
|
by: zr |
last post by:
Hi,
i need to read a text file which contains a list of items, all of type
ItemType, separated by whitespace and newlines. For each line, there
will be a vector<ItemTypeobject that will store the integers read in
that line. There will be a single vector<vector<ItemType>object that
will stores all of the vector<ItemTypeobjects mentioned in the
previous sentence.
I wrote a quick implementation and it seems to be working, but i would
like...
|
by: nirmala26 |
last post by:
Hi All,
Language Used - C#.net
I have a web application containing 6 aspx pages and their code files. Now I want to design a automatic display of these webpages in sequence. In detail, once i open the weblink - it should show the Main webpage (Main.aspx) for 2 mins, then automatically redirect to the second webpage (Second.aspx), display this for 2 mins and then redirect to the third and so on... Once the 6th webpage (Six.aspx) is displayed...
|
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: 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: 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: 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
|
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...
| |