Hello enthusiast programmers, It seems I am very bad at manipulating lists in Python (I come from the IDL world, and I really struggle with Python). I have a list of string, say:
mylist =['boring', 'enjoyable', 'great']
and a string, say:
s = 'Python is '
and I want to build the list: ['Python is boring', 'Python is enjoyable', 'Python is great']
mynewlist = s + l
as I would have simply done in IDL, doesn't work of course ... I am not able to do it simply! (ie without a loop and intermediate variables)
Thanks for the help!
s.
that would be:
newlist = [s + x for x in mylist]
You basically carry out the same addition for each element of mylist; the result is a list itself. The way it is done is called list comprehension, one of the most powerful tools for list manipulation.
Use map
or list comprehensions:
map(lambda x: "Python is " + x, mylist)
["Python is " + x for x in mylist]
Both solutions will do an implicit loop, just like IDL would; it is inevitable to have one in this scenario. But no overt loop like for ...:
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.