Python "join" on both sides of strings? - python

l = ['1','2','3']
goal = ['<li>1</li>','<li>2</li>']
How can I get goal from l?
I'm playing with list comprehensions but it's messy!

Try string formatting and list comprehension, like so.
goal = ['<li>{0}</li>'.format(x) for x in l]

Two options using str.format():
goal = map('<li>{0}</li>'.format, l)
... or...
goal = ['<li>{0}</li>'.format(x) for x in l]
Note that on Python 3.x map() will return an iterator instead of a list, so if you want a list you would need to use list(map(...)).

With string.format method
goal = ['<li>{0}</li>'.format(sym) for sym in l]

Related

Converting to float a list of lists containing strings

I have this List of lists containing string values:
List = [['138.314038', '-35.451642'],
['138.313946', '-35.45212'],
['138.313395', '-35.45291'],
['138.312425', '-35.453978'],
['138.311697', '-35.454879'],
['138.311042', '-35.45569'],
['138.310407', '-35.45647'],
['138.315603', '-35.44981'],
['138.315178', '-35.450241'],
['138.314603', '-35.450948'],
['138.314038', '-35.45164']]
I am trying to transform each string value in the list of lists into a float value.
I was trying:
results = [float(i) for i in List]
But I am only indexing the lists and not the values inside. How can I do it using a similar approach and keeping the same structure of the variable List.
You have list, so use a double comprehension:
results = [[float(i) for i in e] for e in List]
I am using numpy convert it
np.array(List).astype(float).tolist()
Out[185]:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
Maybe ugly using two list maps:
print(list(map(lambda x: list(map(float,x)), List)))
Output:
[[138.314038, -35.451642], [138.313946, -35.45212], [138.313395, -35.45291], [138.312425, -35.453978], [138.311697, -35.454879], [138.311042, -35.45569], [138.310407, -35.45647], [138.315603, -35.44981], [138.315178, -35.450241], [138.314603, -35.450948], [138.314038, -35.45164]]
Print it better:
pprint.pprint(list(map(lambda x: list(map(float,x)), List)))
Output:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
#you can use map function as well
results = [list(map(float,x)) for x in List]
you can expand the list, like this:
results = [list(map(float, l)) for l in List]
You could use map to achieve it.
floats = [ list(map(float, i)) for i in List ]

Extract substrings from a list into a list in Python

I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])

how to use lambda to unpack this list [(a,b),(c,d),...] in python3

there. I want to use lambda function to unpack a list like this [(a,b),(c,d),...]
For example, now I have two lists like this:
list1 = [1,2,3]
list2 = [0.1,0.2,0.3]
Then I can use zip function to generate a new list like this:
l = zip(list1,list2)
Here, l = [(1,0.1),(2,0.2),(3,0.3)]
And I want to do the operation on this list l like this:
outcome_l = [1*0.1, 2*0.2, 3*0.3]
As I know the easiest way is to define a lambda function looks like this:
f = lambda l1,l2:l1*l2
And then I may want to use this lambda function like this to get the outcome:
outcome_l = list(map(f,l))
But the problem in here is that it seems lambda function is hard to unpack every set in the list l, and it keeps saying me there exists an error as " < lambda > () takes 2 positional arguments but 3 were given", that is the length of list l is 3.
So do you know how to deal with this problem in python3? It seems that python2 may not suffer the same problem.
Your function f (which, since you're naming it, you should've defined in the traditional way) takes two arguments. Each item in l is a single object - a tuple. The easiest way to solve this is with comprehensions, which are so versatile that they nearly prompted Python's designers to remove map from the language.
outcome_l = [a*b for a,b in l]
You could even use the function f in this manner, with * unpacking:
outcome_l = [f(*item) for item in l]
You can use operator.mul with your map to get your desired result. This function does the same thing as what you want.
Taken from the docs map(mul, list1, list2)
To make your function work you could use f = lambda x: x[0] * x[1]
l = [(1,0.1),(2,0.2),(3,0.3)]
outcome_l = [i*j for i, j in l]
or better:
list1 = [1,2,3]
list2 = [0.1,0.2,0.3]
outcome_l = [i*j for i, j in zip(list1, list2)]

Accessing elements of a python list separated by a special character

I have a python list which looks like this :
['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
Currently I am accessing specific portions of each element of the list like NEW or joe by splitting each element by : creating a list of list like :
[['NEW','kim','OPERATOR'], ['DELETE','joe','USER_ROLE_GUEST']]
and then accessing it like list[i][j].
Is there any nice pythonic way of avoiding all this and directly accessing the elements that I need ?
If your purpose (which is not clear) is to not create a new list (which may be costly if the original list is large), and the data structure is always the same, you could split the internal string on the fly:
a = ['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
a[0].split(":")[0] # returns NEW
By the way, transforming your list in a list of tuples (or better, namedtuples) would be a better approach from a programming POV.
You can use the following function :
>>> def find_element(i,j,li):
... try:
... return li[i].split(':')[j]
... except IndexError:
... print 'your index is out of range'
...
>>> l =['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
>>> find_element(1,4,l)
your index is out of range
>>> find_element(1,2,l)
'USER_ROLE_GUEST'
You could use a generator expression and pop the elements of as needed:
l = ['NEW:kim:OPERATOR', 'DELETE:joe:USER_ROLE_GUEST']
spl = (sub.split(":") for sub in l)
a = next(spl)
print(a[0])
b = next(spl)
print(b[0])
Or simply a generator expression and iterate over:
spl = (sub.split(":") for sub in l)
for ele in spl:
print(ele)
['NEW', 'kim', 'OPERATOR']
['DELETE', 'joe', 'USER_ROLE_GUEST']

How do I merge a 2D array in Python into one string with List Comprehension?

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.
Say, I have a 2D list:
li = [[0,1,2],[3,4,5],[6,7,8]]
I would like to merge this either into one long list
li2 = [0,1,2,3,4,5,6,7,8]
or into a string with separators:
s = "0,1,2,3,4,5,6,7,8"
Really, I'd like to know how to do both.
Like so:
[ item for innerlist in outerlist for item in innerlist ]
Turning that directly into a string with separators:
','.join(str(item) for innerlist in outerlist for item in innerlist)
Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:
for innerlist in outerlist:
for item in innerlist:
...
Try that:
li=[[0,1,2],[3,4,5],[6,7,8]]
li2 = [ y for x in li for y in x]
You can read it like this:
Give me the list of every ys.
The ys come from the xs.
The xs come from li.
To map that in a string:
','.join(map(str,li2))
There's a couple choices. First, you can just create a new list and add the contents of each list to it:
li2 = []
for sublist in li:
li2.extend(sublist)
Alternately, you can use the itertools module's chain function, which produces an iterable containing all the items in multiple iterables:
import itertools
li2 = list(itertools.chain(*li))
If you take this approach, you can produce the string without creating an intermediate list:
s = ",".join(itertools.chain(*li))
My favorite, and the shortest one, is this:
li2 = sum(li, [])
and
s = ','.join(li2)
EDIT: use sum instead of reduce, (thanks Thomas Wouters!)
For the second one, there is a built-in string method to do that :
>>> print ','.join(str(x) for x in li2)
"0,1,2,3,4,5,6,7,8"
For the first one, you can use join within a comprehension list :
>>> print ",".join([",".join(str(x) for x in li])
"0,1,2,3,4,5,6,7,8"
But it's easier to use itertools.flatten :
>>> import itertools
>>> print itertools.flatten(li)
[0,1,2,3,4,5,6,7,8]
>>> print ",".join(str(x) for x in itertools.flatten(li))
"0,1,2,3,4,5,6,7,8"
N.B : itertools is a module that help you to deal with common tasks with iterators such as list, tuples or string... It's handy because it does not store a copy of the structure you're working on but process the items one by one.
EDIT : funny, I am learning plenty of way to do it. Who said that there was only one good way to do it ?
import itertools
itertools.flatten( li )
To make it a flattened list use either:
http://code.activestate.com/recipes/121294/
http://code.activestate.com/recipes/363051/
Then, join to make it a string.
Here is a way:
def convert2DArrtostring(ndArr):
'''converts 2D array to string'''
arr_str = "["
for i in ndArr:
arr_str += "["
for j in i:
arr_str += str(j) + " "
arr_str += "]\n"
arr_str += "]"
return arr_str
There are many ways to do this problem. I like Numpy's tools because it is normally already imported in everything I do. However, if you aren't using Numpy for anything else this probably isn't a good method.
import numpy
li = [[0,1,2],[3,4,5],[6,7,8]]
li2=li[0] #first element of array to merge
i=1
while i<len(li):
li2=numpy.concatenate((li2,li[i]))
i+=1
print li2
This would print [0 1 2 3 4 5 6 7 8] and then you can convert this into your string too.

Categories