replace substrings in list - python

I am looking forward to get rid of a space that is after each element in my list:
list1 = ['Aena', 'Cellnex Telecom', 'Amadeus', 'Abertis']
in order to obtain the list like this:
list1 = ['Aena','Cellnex Telecom','Amadeus','Abertis']
I have tried the following loop but returns the same initial list:
new_list = [stocks.replace(" ","") for stocks in list1]
and
new_list = [stocks.replace(", '",",'") for stocks in list1]
print(new_list)
Could anyone help me to obtain the desired list without the spaces?

I think you have to understand, that print(..) prints the representation of a list (which is a comma separated list surrounded by square brackets).
With the list comprehension, you alter the elements themselves. As far as I know you can't do much about how print prints the list itself. But you can write your own print method.
We can do this by using a join on the repr(..) of the elements, and surround it by square brackets, like:
print('[{}]'.format(','.join(repr(x) for x in list1)))
This prints:
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']

>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']

Related

Join elements of an arbitrary number of lists into one list of strings python

I want to join the elements of two lists into one list and add some characters, like so:
list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']
joined_list = ['some1_thing1', 'some2_thing2', 'some3_thing3']
however i don't know in advance how many lists I will have to do this for, i.e. I want to do this for an arbitrary number of lists
Also, I currently receive a list in the following form:
list_A = [('some1','thing1'),('some2','thing2'),('some3','thing3')]
so I split it up into lists like so:
list_B = [i for i in zip(*list_A)]
I do this because sometimes I have an int instead of a string
list_A = [('some1','thing1',32),('some1','thing1',42),('some2','thing3', 52)]
so I can do this after
list_C = [list(map(str,list_B[i])) for i in range(0,len(list_B)]
and basically list_1 and list_2 are the elements of list_C.
So is there a more efficient way to do all this ?
Try this if you are using python>=3.6:
[f'{i}_{j}' for i,j in zip(list_1, list_2)]
If you using python3.5, you can do this:
['{}_{}'.format(i,j) for i,j in zip(list_1, list_2)]
also you can use this if you don't want to use formatted string:
['_'.join([i,j]) for i,j in zip(list_1, list_2)]
You can join function like this on the base list_A, itself, no need to split it for probable int values:
list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)]
["_".join(map(str, i)) for i in list_A]
Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52']
Update:
For you requirement, where you want to ignore last element for last tuple in your list_A, need to add if-else condition inside the list-comprehension as below:
["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A ]
Updated Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']
For ignoring the last element of every tuple in list_A, I found this to be the quickest way:
["_".join(map(str, i)) for i in [x[:-1] for x in list_A] ]

How to access certain elements of a list of lists?

I'm not sure what I need to do here.
I have a list which contains sublists:
my_list = [
[string_0, string2, [int1, int2], [int3, float1]],
[string_01, string2_2, [int1_1, int2_2], [int3_3, float1_1]]
]
which goes on like this for a bit.
How do I get certain parts from my_list to create a new list containing certain items from my_list? For example:
new_list = [string_01, string2, int1, float1_1]
So far I was trying to use a list comprehension but I couldn't get it to work because I only got it to print one sublist (ie: string_0, string2, [int1, int2], [int3, float1]) and not specific parts.
To get the elements you showed in your example:
new_list=[ [i[0], i[1], i[2][0], i[3][1] ] for i in my_list]
print (new_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:])

While loop with single quotes for a condition in Python

I came across the following line of code in Python and I keep wondering what does it do exactly:
while '' in myList:
myList.remove('')
Thanks in advance.
It removes all empty strings from a list, inefficiently.
'' in myList tests if '' is a member of myList; it'll loop over myList to scan for the value. myList.remove('') scans through myList to find the first element in the list that is equal to '' and remove it from the list:
>>> myList ['', 'not empty']
>>> '' in myList
True
>>> myList.remove('')
>>> myList
['not empty']
>>> '' in myList
False
So, the code repeatedly scans myList for empty strings, and each time one is found, another scan is performed to remove that one empty string.
myList = [v for v in myList if v != '']
would be a different, more efficient way of accomplishing the same task. This uses a list comprehension; loop over all values in myList and build a new list object from those values, provided they are not equal to the empty string.
Put simply, it removes all empty strings from myList.
Below is a breakdown:
# While there are empty strings in `myList`...
while '' in myList:
# ...call `myList.remove` with an empty string as its argument.
# This will remove the one that is currently the closest to the start of the list.
myList.remove('')
Note however that you can do this a lot better (more efficiently) with a list comprehension:
myList = [x for x in myList if x != '']
or, if myList is purely a list of strings:
# Empty strings evaluate to `False` in Python
myList = [x for x in myList if x]
If myList is a list of strings and you are on Python 2.x, you can use filter, which is even shorter:
myList = filter(None, myList)
In Python, two single quotes '' or double quotes "" represent the empty string.
The condition to keep looping is while the empty string exists in the list, and will only terminate when there are no more empty strings.
Therefore, it removes all empty strings from a list.

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