Splitting a list with a separator - python

I have written a function that gets two arguments: a list and one value that is present in the list previously given (sep). The purpose of the function is to split the given list and return multiple lists in list without the value that was specified in the second argument of the written fuction. So with def split_list([1,2,3,2,1],2) ---> result would be [[1],[3],[1]]. The functionality of spliting is good but the result keeps the second value of the function (sep) in the separated lists. I couldnt think of a way how to solve this problem. Thanks in advance
def split_list(l, sep):
occurence = [i for i, x in enumerate(l) if x == sep]
newlist=[]
newlist.append(l[:occurence[0]])
for i in range(0,len(occurence)):
j=i+1
if j < len(occurence):
newlist.append(l[occurence[i]:occurence[j]])
i+=1
newlist.append(l[occurence[-1]:])
return newlist

How about this:
def split_list(l, sep):
nl = [[]]
for el in l:
if el == sep:
nl.append([])
else:
# Append to last list
nl[-1].append(el)
return nl
Or with your method, by using the list of occurences:
def split_list(l, sep):
# occurences
o = [i for i, x in enumerate(l) if x == sep]
nl = []
# first slice
nl.append(l[:o[0]])
# middle slices
for i in range(1, len(o)):
nl.append(l[o[i-1]+1:o[i]])
# last slice
nl.append(l[o[-1]+1:])
return nl

you can split your list with below list comprehension and zip function :
>>> l=[1,2,3,2,1,8,9]
>>> oc= [i for i, x in enumerate(l) if x == 2]
>>> [l[i:j] if 2 not in l[i:j] else l[i+1:j] for i, j in zip([0]+oc, oc+[None])]
[[1], [3], [1, 8, 9]]
So for your function :
def split_list(l, sep):
occurence = [i for i, x in enumerate(l) if x == sep]
return [l[i:j] if sep not in l[i:j] else l[i+1:j] for i, j in zip([0]+occurence, occurence+[None])]

Use [list(x) for i, x in enumerate(l) if x != sep]

Related

return all indices of first elements in a list where subsequent values increase incrementally

Need to find indices very similar to here
But I have a list of multiple groups of incrementing values, e.g.
lst = [0,1,2,7,8,9]
Expected output: [0,3]
Version with a simple loop:
lst = [0,1,2,7,8,9]
prev = float('-inf')
out = []
for i,v in enumerate(lst):
if v!=prev+1:
out.append(i)
prev = v
out
Same thing with a list comprehension and zip:
out = [i for i, (a,b) in enumerate(zip([float('-inf')]+lst, lst)) if a+1!=b]
Variant with itertools.pairwise (python ≥3.10):
from itertools import pairwise
out = [0]+[i for i, (a,b) in enumerate(pairwise(lst), start=1) if a+1!=b]
output: [0, 3]

How to find the postion of certain string in the list using abstract function

I am trying to find the position of certain string s in the list, but ONLY using the abstract function (ie. filter, map...).
find_all([], "") => []
find_all(["a","v","c","w","v"], "v") => [1,4]
I have tried the filter, but I don't know how to add the position in.
Use enumerate with list comprehension:
def find_all(l, k):
return [i for i,j in enumerate(l) if j == k]
Test:
find_all(["a","v","c","w","v"], "v")
find_all([], "")
Output:
[1, 4]
[]
Maybe something like this?
[item[0] for item in list(filter(lambda x : x[1] == 'v',enumerate(x)))]
Output:
[1, 4]

Taking a list and printing all of the indexes of the elements that aren't equal to 0

I have to take a list such as [2,2,0,2] and I then need to return a new list of the indexes for the elements in the list that are not 0 so for the list of [2,2,0,2] I would need to return [0,1,3]. Or for [1,0,1,1] I would need to return [0,2,3].
def test(B):
for k in list(B):
if k > 0:
result = []
for i in range(len(B)):
result.append(i)
return result
test([2,2,0,2])
->[0,1,2,3]
My issue is that all of the indexes get returned and I have tried to fix this but have had no luck. If anyone could help that'd me great, thanks.
You can use enumerate to achieve this neatly:
def legal(B):
return [i for i, x in enumerate(B) if x]
# or if you want to cover more than numbers
# return [i for i, x in enumerate(B) if x != 0]
>>> legal([2,2,0,2])
[0, 1, 3]
>>> legal([1,0,1,1])
[0, 2, 3]
this should do the work :
def indices(some_list):
indices_list = []
for i in range(0, len(some_list)):
if some_list[i] != 0:
indices_list.append(i)
return indices_list
you can use list comprehension like below
ls = [2,2,0,2]
ind = [i for i, val in enumerate(ls) if val!=0]
print(ind)
You could try this:
def legal(B):
result = []
for i, k in enumerate(list(B)):
if k > 0:
result.append(i)
return result
Why are you doing list(B)? If B is not a list then this should work. If it is you should remove the list function.

Lists in python 3

So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function.
l1 = []
def fun2(x,y):
for x in range(x+1):
for y in range(y+1):
l1.append((x,y))
return l1
You can avoid duplicate tuple elements while generating the list. Just add an if:
def fun2(x, y):
result = []
for a in range(x+1):
for b in range(y+1):
if a != b:
result.append((a,b))
return result
This could also be written more succinctly as a list comprehension:
result = [(a, b) for a in range(x+1) for b in range(y+1) if a != b]
Yet another option is to use itertools.product():
from itertools import product
result = [(a, b) for a, b in product(range(x+1), range(y+1)) if a != b]
Removing items afterwards is also possible with a list comprehension:
result = [pair for pair in result if pair[0] != pair[1]]
which creates a new list without the duplicate items then rebinds it to result. You can overwrite the list in place with:
result[:] = [pair for pair in result if pair[0] != pair[1]]
Method 1: Using list comprehnsion:
lst = [c for c in l1 if c[0] != c[1]]
Method 2: Building the list manually:
lst = []
for elem in l1:
if elem[0] != elem[1]:
lst.append(elem)

Delete first two characters of elements in a list of lists

Let's say I have the following list of lists:
final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]
Now I need to remove the first 2 characters of the second element of every list, so the result will be:
final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]
No need to rebuild the entire list from scratch just to do it in a one-line comprehension while unnecessarily iterating the inner lists. Just modify the elements that need modifying:
for lst in final_list:
lst[1] = lst[1][2:]
use double list comprehensions:
final_list = [[x if hasattr(x, '__len__') and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
this will trim the first 2 elements of the second element, even if the element is not a string
If you want it for strings only then the statement becomes:
final_list = [[x if type(x) == str and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
final_list = [[x[2:] if i==1 else x for i, x in enumerate(y)] for y in my_list]
Full answer:
final_list = []
for y in my_list:
l = []
for i, x in enumerate(my_list):
if i==1: #2nd element in the list
l.append(x[2:]) # Append a string starting from the 3rd letter to the end
else:
l.append(x) . # Just append the element at x
my_list.append(l) # Append the list l to my_list
print(my_list)

Categories