remove list items from list of list in python - python

I have a list of characters:
Char_list = ['C', 'A', 'G']
and a list of lists:
List_List = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
I would like to remove each Char_list[i] from the list of corresponding index i in List_List.
Output must be as follows:
[['A','T'], ['C', 'T', 'G'], ['A', 'C']]
what I am trying is:
for i in range(len(Char_list)):
for j in range(len(List_List)):
if Char_list[i] in List_List[j]:
List_List[j].remove(Char_list[i])
print list_list
But from the above code each character is removed from all lists.
How can I remove Char_list[i] only from corresponding list in List_list?

Instead of using explicit indices, zip your two lists together, then apply a list comprehension to filter out the unwanted character for each position.
>>> char_list = ['C', 'A', 'G']
>>> list_list = [['A', 'C', 'T'], ['C','A', 'T', 'G'], ['A', 'C', 'G']]
>>> [[x for x in l if x != y] for l, y in zip(list_list, char_list)]
[['A', 'T'], ['C', 'T', 'G'], ['A', 'C']]

You may use enumerate with nested list comprehension expression as:
>>> char_list = ['C', 'A', 'G']
>>> nested_list = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
>>> [[j for j in i if j!=char_list[n]] for n, i in enumerate(nested_list)]
[['A', 'T'], ['C', 'T', 'G'], ['A', 'C']]
I also suggest you to take a look at PEP 8 - Naming Conventions. You should not be using capitalized first alphabet with the variable name.

Char_list = ['C', 'A', 'G']
List_List = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
for i in range(len(Char_list)):
List_List[i].remove(Char_list[i])
print(List_List)
OUTPUT
[['A', 'T'], ['C', 'T', 'G'], ['A', 'C']]
If the characters repeat in nested lists, Use this
Char_list = ['C', 'A', 'G']
List_List = [['A', 'C','C','C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
for i in range(len(Char_list)):
for j in range(List_List[i].count(Char_list[i])):
List_List[i].remove(Char_list[i])
print(List_List)

Related

How to handle the situation if one iterator runs out while iterating through multiple lists in python using zip?

here is the code:-
array1 = [["a","b","c"] ,['e','f','g'] , ['i','j','k']]
array2 = ['d' , 'h']
array1 = [a+list(b) for a,b in zip(array1,array2)]
print(array1)
I want the desired output [["a","b","c", "d"] ,['e','f','g','h'] , ['i','j','k']] but the code gives the optput [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']].
This is happening because there is nothing to add to in array1[2], how to overcome this situation,
I tried using a = [a+list(b) if b else a for a,b in zip(array1,array2)] but there was no change please help.
zip ends prematurely in this case. You can use itertools.zip_longest instead, with a default fillvalue:
from itertools import zip_longest
print([a+b for a, b in zip_longest(array1, map(list, array2), fillvalue=[])])
Output:
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k']]
>>>
You can do using simple for loop
array1 = [["a","b","c"] ,['e','f','g'] , ['i','j','k']]
array2 = ['d' , 'h']
for i in range(len(array2)):
array1[i].append(array2[i]) #[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k']]
print(array1)
And also using list comprehension
array1 = [array1[i]+[array2[i]] if i<len(array2) else array1[i] for i in range(len(array1))]
Here you go:
array1 = [["a","b","c"] ,['e','f','g'] , ['i','j','k']]
array2 = ['d' , 'h']
A=array1[0]
B=array1[1]
A.append(array2[0])
B.append(array2[1])
print(array1)
Output:
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k']]

How to split a list and into a tuple

If i have a list
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
and I want to split into new list without 'k', and turn it into a tuple. So I get
(['a'],['b', 'c'], ['d', 'e', 'g'])
I am thinking about first splitting them into different list by using a for loop.
new_lst = []
for element in lst:
if element != 'k':
new_ist.append(element)
This does remove all the 'k' but they are all together. I do not know how to split them into different list. To turn a list into a tuple I would need to make a list inside a list
a = [['a'],['b', 'c'], ['d', 'e', 'g']]
tuple(a) == (['a'], ['b', 'c'], ['d', 'e', 'g'])
True
So the question would be how to split the list into a list with sublist.
You are close. You can append to another list called sublist and if you find a k append sublist to new_list:
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
new_lst = []
sublist = []
for element in lst:
if element != 'k':
sublist.append(element)
else:
new_lst.append(sublist)
sublist = []
if sublist: # add the last sublist
new_lst.append(sublist)
result = tuple(new_lst)
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])
If you're feeling adventurous, you can also use groupby. The idea is to group elements as "k" or "non-k" and use groupby on that property:
from itertools import groupby
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
result = tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k)
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])
Thanks #YakymPirozhenko for the simpler generator expression
tuple(list(i) for i in ''.join(lst).split('k'))
Output:
(['a'], ['b', 'c'], ['d', 'e', 'g'])
Here's a different approach, using re.split from the re module, and map:
import re
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
tuple(map(list, re.split('k',''.join(lst))))
(['a'], ['b', 'c'], ['d', 'e', 'g'])
smallerlist = [l.split(',') for l in ','.join(lst).split('k')]
print(smallerlist)
Outputs
[['a', ''], ['', 'b', 'c', ''], ['', 'd', 'e', 'g']]
Then you could check if each sub lists contain ''
smallerlist = [' '.join(l).split() for l in smallerlist]
print(smallerlist)
Outputs
[['a'], ['b', 'c'], ['d', 'e', 'g']]
How about slicing, without appending and joining .
def isplit_list(lst, v):
while True:
try:
end = lst.index(v)
except ValueError:
break
yield lst[:end]
lst = lst[end+1:]
if len(lst):
yield lst
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g', 'k']
results = tuple(isplit_list(lst, 'k'))
Try this, works and doesn't need any imports!
>>> l = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
>>> t = []
>>> for s in ''.join(l).split('k'):
... t.append(list(s))
...
>>> t
[['a'], ['b', 'c'], ['d', 'e', 'g']]
>>> t = tuple(t)
>>> t
(['a'], ['b', 'c'], ['d', 'e', 'g'])
Why don't you make a method which will take a list as an argument and return a tuple like so.
>>> def list_to_tuple(l):
... t = []
... for s in l:
... t.append(list(s))
... return tuple(t)
...
>>> l = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
>>> l = ''.join(l).split('k')
>>> l = list_to_tuple(l)
>>> l
(['a'], ['b', 'c'], ['d', 'e', 'g'])
Another approach using itertools
import more_itertools
lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
print(tuple(more_itertools.split_at(lst, lambda x: x == 'k')))
gives
(['a'], ['b', 'c'], ['d', 'e', 'g'])

How to make a jagged array neat in Python?

I have an array like this: ['a', ['e', 'r', 't'], 'c'].
I want to use some sort of processing to make the array neat:
[['a', 'e', 'c'], ['a', 'r', 'c'], ['a', 't', 'c']].
If the array is: ['a', ['e', 'r', 't'], ['c', 'd']].
The result is:
[['a', 'e', 'c'], ['a', 'e', 'd'], ['a', 'r', 'c'], ['a', 'r', 'd'], ['a', 't', 'c'], ['a', 't', 'd']].
And the length of the array is not fixed to 3, other examples:
['a', 'b'] = > ['a', 'b']
['a', ['b', 'c']] => [['a', 'b'], ['a', 'c']]
['ab', ['b', 'c']] => [['ab', 'b'], ['ab', 'c']]
[[1, 2], 3, 4] => [[1, 3, 4], [2, 3, 4]]
So what should I do? Is there a solution in Numpy?
Unless I misunderstand the question, you just want the product of the sub-lists, although you have to wrap any single elements into lists first.
>>> from itertools import product
>>> arr = ['a', ['e', 'r', 't'], ['c', 'd']]
>>> listified = [x if isinstance(x, list) else [x] for x in arr]
>>> listified
[['a'], ['e', 'r', 't'], ['c', 'd']]
>>> list(product(*listified))
[('a', 'e', 'c'),
('a', 'e', 'd'),
('a', 'r', 'c'),
('a', 'r', 'd'),
('a', 't', 'c'),
('a', 't', 'd')]
I have a recursive solution:
inlist1 = ['ab', ['e', 'r', 't'], ['c', 'd']]
inlist2 = [['a', 'b'], ['e', 'r', 't'], ['c', 'd']]
inlist3 = [['a', 'b'], 'e', ['c', 'd']]
def jagged(inlist):
a = [None] * len(inlist)
def _jagged(index):
if index == 0:
print(a)
return
v = inlist[index - 1]
if isinstance(v, list):
for i in v:
a[index - 1] = i
_jagged(index - 1, )
else:
a[index - 1] = v
_jagged(index - 1)
_jagged(len(inlist))
jagged(inlist3)

How to create list of lists from flat list in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a list:
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Is there a way to create a list of lists so that:
l = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
And would it be possible to create the list of lists where the lists are of different sizes? For example:
l = [['a', 'b'], ['c', 'd', 'e', 'f'], ['g'], ['h', 'i']]
1 . For a multi-dimensioned list of defined inner list size :
>>> inner_size = 3
>>> out = [ l[i:i+inner_size] for i in range(0, len(l), inner_size) ]
>>> out
=> [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
2 . For a multi-dimensioned list of random inner list size (this is kind of chunky unfortunately) :
>>> import random
>>> i=0
>>> out = []
>>> while i<len(l):
left_out = len(l) - i
inner_size = random.randint(1,left_out)
out.append(l[i: i+inner_size])
i += inner_size
>>> out
=> [['a'], ['b'], ['c', 'd', 'e', 'f', 'g'], ['h', 'i']]
For a consistent chunk size n, you can do:
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
n = 3
l2 = [l[i:i + n] for i in range(0, len(l), n)]
l2
# [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
Given split indexes (which you can easily generate from a list of chunk sizes), you can produce custom slices:
splits = [0, 2, 6, 7, 9]
l2 = [l[start:end] for start, end in zip(splits, splits[1:])]
l2
# [['a', 'b'], ['c', 'd', 'e', 'f'], ['g'], ['h', 'i']]
Here is a simple solution, you can set your own chunk sizes in the variable chunk_sizes either as a list or tuple or an integer
def chunk_list(l,chunk_sizes):
if isinstance(chunk_sizes,int):
for i in range(0,len(l),chunk_sizes):
yield l[i:i + chunk_sizes]
else:
start = 0
for size in chunk_sizes:
if start < len(l):
yield l[start:start + size]
start += size
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
# custom chunk_sizes list
chunk_sizes = [2,4,1,2]
print ([sl for sl in chunk_list(l,chunk_sizes)])
#prints [['a', 'b'], ['c', 'd', 'e', 'f'], ['g'], ['h', 'i']]
# integer chunk_sizes
chunk_sizes = 3
print ([sl for sl in chunk_list(l,chunk_sizes)])
#prints [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

Switch first and last elements of two lists in Python

In Python, I have two lists that either have equal number of elements (e.g. 8 and 8) or one less than the other (e.g. 7 and 8; 3 and 4):
list1 = ['A', 'B', 'C', 'D']
list2 = ['E', 'F', 'G', 'H']
or
list3 = ['A', 'B', 'C']
list4 = ['D', 'E', 'F', 'G']
I'm trying to figure out the best way to build an algorithm that will switch the last half of the first list with the first half of the last list, resulting in this, when both lists have an even number of elements:
switched_list1 = ['A', 'B', 'E', 'F']
switched_list2 = ['C', 'D', 'G', 'H']
…and this when the one of the lists has an odd number:
switched_list3 = ['A', 'D', 'E']
switched_list4 = ['B', 'C', 'F', 'G']
What's the most efficient way to build an algorithm that can switch list elements like this?
list1 = ['A', 'B', 'C']
list2 = ['D', 'E', 'F', 'G']
nlist1 = len(list1)/2
nlist2 = len(list2)/2
new1 = list1[:nlist1] + list2[:nlist2]
new2 = list1[nlist1:] + list2[nlist2:]
print new1
print new2
produces
['A', 'D', 'E']
['B', 'C', 'F', 'G']
>>> def StrangeSwitch(list1,list2):
return (list1[:len(list1)/2]+list2[:len(list2)/2],list1[len(list1)/2:]+list2[len(list2)/2:])
>>> list1 = ['A', 'B', 'C', 'D']
>>> list2 = ['E', 'F', 'G', 'H']
>>> (list1,list2)=StrangeSwitch(list1,list2)
>>> list1
['A', 'B', 'E', 'F']
>>> list2
['C', 'D', 'G', 'H']
>>> list3 = ['A', 'B', 'C']
>>> list4 = ['D', 'E', 'F', 'G']
>>> (list3,list4)=StrangeSwitch(list3,list4)
>>> list3
['A', 'B', 'C']
>>> list4
['B', 'C', 'F', 'G']
>>>
Reading the Comments by OP I would take the priviledge of proposing another approach
>>> def StrangeSwitchFast(list1,list2):
#return (list1[:len(list1)/2]+list2[:len(list2)/2],list1[len(list1)/2:]+list2[len(list2)/2:])
return (list(itertools.chain(itertools.islice(list1,0,len(list1)/2),itertools.islice(list2,0,len(list2)/2))),
list(itertools.chain(itertools.islice(list1,len(list1)/2,None),itertools.islice(list2,len(list2)/2,None))))
The above doesn't create any temporary list and if OP desires to use it as an iterator rather than a list for the downstream processing, then the list can be safely dropped from the function and can be left to return as a tuple of iterators.

Categories

Resources