I need to delete these lists inside of list that contains the / symbol.
List for example:
X = [['a/','$1'], ["c","d"]]
so X[0] should be deleted. The actual list are much longer and contains more instances of this condition.
I tried use something like:
print([l for l in X if l.count("/") <1])
But if I understand correctly because the / is attached to another symbol he is not counted.
Should I convert this list of lists to string, separate the / from another character, and then use the count function, or there is better solution?
One way to search "/" in each item in the sublists is to wrap a generator expression with any. Since you don't want sublists with "/" in it, the condition should be not any():
out = [lst for lst in X if not any('/' in x for x in lst)]
Output:
[['c', 'd']]
The call to filter() applies that lambda function to every list in X and filters out list with '/'.
result = list(filter(lambda l: not any('/' in s for s in l), X))
counter = 0
while counter < len(X):
removed = False
for i in X[counter]:
if '/' in i:
X.pop(counter)
removed = True
break
if not removed:
counter += 1
Given:
X = [['a/','$1'], ["c","d"]]
You can convert the sub lists to their repr string representations and detect the / in that string:
new_x=[sl for sl in X if not '/' in repr(sl)]
Or, you can use next:
new_x=[sl for sl in X if not next('/' in s for s in sl)]
Either:
>>> new_x
[['c', 'd']]
I have two lists and I want to use a list comprehension to create a list of lists. The first list has some prefixes and the second has some suffixes.
prefixes = ['t1_', 't0_']
suffixes = ['price', 'sales']
The list comprehension should return
output = [['t1_price', 't1_sales'],
['t0_price', 't0_sales']]
I am able to accomplish this with a pair of for loops:
output = []
for prefix in prefixes:
pairs = []
for suffix in suffixes:
pairs.append(prefix + suffix)
output.append(pairs)
But I think a list comprehension would improve my code's readability.
How can I accomplish this?
You can also achieve this using list comprehension
[[p+s for s in suffixes] for p in prefixes]
#[['t1_price', 't1_sales'], ['t0_price', 't0_sales']]
an alternative using a generator that does not require a nested comprehension
from itertools import product
[a+b for (a, b) in product(prefixes, suffixes)]
output = [[x+y for x in prefixes] for y in suffixes]
print(output)
I have this list:
list1 = [['123'], ['456'], ['789']]
I want to convert this list into a string and later store it into a column in a database in this form:
123 / 456 / 789
I tried doing this:
s2 = ", ".join(repr(e) for e in list1)
print(s2)
But this is what I'm getting:
['123'], ['456'], ['789']
Any ideas on what should I do next to get the desired output?
You are close, but what you want to do is flatten your list of lists first, then convert to string. Like this:
" / ".join([item for sublist in list1 for item in sublist])
You can use itertools.chain
import itertools
list1 = [['123'], ['456'], ['789']]
", ".join(itertools.chain(*list1))
# => '123, 456, 789'
list1 = [['123'], ['456'], ['789']]
st = [ '/' + x[0] for x in list1]
st = ''.join(st)
print(st)
output
/123/456/789
Since you have lists in the list, you need to get the first indice so this helps you
" / ".join(map(lambda x:x[0],list1))
If you specifically only ever want the first element of a sublist even if it's got more than one element, then I think this one-liner is the clearest:
s2 = ' / '.join( x[0] for x in list1 )
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]
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.