I have a list:
lists = (['1','2','3','S','3','4','S','4','6','7'])
And I want to split the list into s smaller list everytime 'S' appears and eliminate 'S' into something like:
([['1','2','3'],['3','4],['4','6','7']])
My code:
def x (lists):
empty = ''
list = []
for x in lists:
if x == empty:
list[-1:].append(x)
else:
list.append([x])
return (list)
I tried something like this, but I am quite new to python, and Im getting nowhere. Nothing fancy please, how would I fix what I have?
Try itertools.groupby():
>>> from itertools import groupby
>>> lists = ['1','2','3','S','3','4','S','4','6','7']
>>> [list(g[1]) for g in groupby(lists, lambda i:i!='S') if g[0]]
[['1', '2', '3'], ['3', '4'], ['4', '6', '7']]
Maybe something like map(list,''.join(lists).split('S'))
Alternately, [list(s) for s in ''.join(lists).split('S'))
Well, may be funny, but this should work:
[s.split('#') for s in '#'.join(lists).split('#S#')]
Instead of the '#' any character can be used if it's unlikely to appear in lists.
Related
I am trying to get all the possible combinations of listA in order of increasing length. This is easy to do, but the current code I have returns Memory error once my list goes above 1000. How do I do the same with a code that does not use as much memory.
original_list = ['1', '2', '3', '4']
#code:
modified_list= [original_list[i:j + 1] for i in range(len(original_list)) for j in range(i + 1, len(original_list))]
print(modified_list)
#output:
#nodified_list = [['1', '2'],['1', '2', '3'],['1', '2', '3', '4'],
['2', '3'],['2', '3', '4'],['3', '4']]
I saw a similar code but this one prints all the combinations of all the elements inside the list.
import itertools
List = []
for L in range(0, len(original_list)+1):
for subset in itertools.combinations(original_list, L):
subset = str(subset).replace('(','[').replace(')',']') #.replace(',','')
List.append(subset)
it's most probably that your modified list that takes up the memory...
try to print the [original_list[i:j + 1] without saving it in another list.
that shouldn't take more memory than your original list size.
Generator expression saves memory a lot, instead of list you can use this:
subsets = (original_list[i:j + 1] for i in range(len(original_list)) for j in range(i + 1, len(original_list)))
Also if you want to print, iterate through each element, do not convert to list.
for i in subsets:
print(i)
I'm trying to remove the odd-indexed elements from my list (where zero is considered even) but removing them this way won't work because it throws off the index values.
lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
def remove_odd_elements(lst):
i=0
for element in lst:
if i % 2 == 0:
pass
else:
lst.remove(element)
i = i + 1
How can I iterate over my list and cleanly remove those odd-indexed elements?
You can delete all odd items in one go using a slice:
del lst[1::2]
Demo:
>>> lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
>>> del lst[1::2]
>>> lst
['712490959', '623726061', '552157404', '1285252944', '1130181076', '552157404', '545600725']
You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.
An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:
lst = [v for i, v in enumerate(lst) if i % 2 == 0]
This keeps the even elements, rather than remove the odd elements.
Since you want to eliminate odd items and keep the even ones , you can use a filter as follows :
>>>filtered_lst=list(filter(lambda x : x % 2 ==0 , lst))
this approach has the overhead of creating a new list.
This question already has an answer here:
Repeat a list within a list X number of times
(1 answer)
Closed 3 years ago.
I want to replicate a list more than 1000 times and then append to a larger list.
For instance:
a = ['1','2','3','4]
When replicating this list and then nesting it a hundred times:
output = [['1','2','3','4],['1','2','3','4],['1','2','3','4],['1','2','3','4],['1','2','3','4].....]
So far I've only come across a*2, which is not want I want.
You can easily replicate the list by the following.
a = ['1','2','3','4']
output = [a]*1000
The above will create reference.
If you need separate copy then do the following.
a = ['1','2','3','4']
output = [a[:] for i in range(1000)]
In that case you should use [a]*2. But note that the * operator will create multiply references to your main object, since it's a mutable object. Instead as a more pythonic way you can use itertools.repeat() which will give you separate copies of your main object:
In [2]: from itertools import repeat
In [5]: a = ['1','2','3','4']
In [6]: list(repeat(a, 4))
Out[6]:
[['1', '2', '3', '4'],
['1', '2', '3', '4'],
['1', '2', '3', '4'],
['1', '2', '3', '4']]
You're very close. While a * 2 may give you [1, 2, 3, 4, 1, 2, 3, 4], there is a way to use that same operator to get the result you want. It's just repeating the contents, so try [a] * 2.
Use list comprehension
>>> b = [a for i in range(3)]
>>> b
[['1', '2', '3', '4'], ['1', '2', '3', '4'], ['1', '2', '3', '4']]
You can do various such operations over lists.
Check this link here
As per my understanding, you need to replicate list without using same reference to perform some operation in future.
you will try this piece of code to generate a list containing n times replicated list
import copy
a = [1,2,3,4]
n = 1000
def replicateMaster(n, a):
output= []
while n != 0:
n -= 1
output.append(copy.deepcopy(a))
return output
Or simply use this shorthand:
import copy
a = [1,2,3,4]
n = 1000
output = [copy.deepcopy(a) for i in range(n)]
hopefully this code is solve your problem
try
output = print([a]*no_of_count)
I have a list:
my_list = ['0300', '0023', '0005', '000030']
I want to remove the preceding zeroes in each string element from the list. So I want strip the 0s from the left side of the string.
Output would be like this:
my_list = ['300', '23', '5', '30']
I've tried this:
for x in my_list:
x = re.sub(r'^0+', "", x)
print my_list
But it doesn't seem to work. Please help!
You can use str.lstrip like this
print [item.lstrip('0') for item in l]
# ['300', '23', '5', '30']
Try:
list = [str(int(el)) for el in list]
Edit: pick the other answer, I'd prefer that one too :-)
From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?
Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]
Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.
try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li