Check if multiple elements are in a list - python

i have 2 lists :
A = ['1', '2', '3', '4', '5']
B = ['0', '1', '9', '3', '0']
and i want to check if elements in list B are in A and return a list, if so it should return the same number, if not it should return empty string '', here is the result i'm looking for :
C = ['', '1', '', '3', '']
i Tried using for loop and append result to an empty list, but i got this :
C = ['', '1', '', '', '', '', '', '', '3', ''...]
it doubled the number of elements in the list cuz it looks for the first number in the entire list then move to second one, which makes sense since i'm using for loop, what should i use instead to get back a 5 elements list please ?
thanks in advance.

To get your required output, you can just loop through B and check if the item exists in A. If it does, then append it in c otherwise append an empty string to c.
A = ['1', '2', '3', '4', '5']
B = ['0', '1', '9', '3', '0']
c = []
for i in B:
if i in A:
c.append(i)
else:
c.append('')
print(c)
The output of the above code
['', '1', '', '3', '']

Related

Can't modify list of lists to have a customized length

I've written a script to make the length of all the lists at least 3 no matter what are their individual length at this moment.
Currently the list of lists I have:
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
I've tried with:
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
for item in item_list:
if len(item)<3:
item.extend([""])
elif len(item)<2:
item.extend([""]*2)
print(item_list)
Output I'm getting:
[['1', '2', ''], ['3', '4', '5'], ['2', '4', '5'], ['1', '']]
Desired output:
[['1', '2', ''], ['3', '4', '5'], ['2', '4', '5'], ['1', '','']]
How can I make the length of all the lists at least 3 irrespective of their current length?
for item in item_list:
item += ['']*(3-len(item))
You have written the order in reverse
item_list = [['1','2'],['3','4','5'],['2','4','5'],['1']]
for item in item_list:
if len(item)<2:
item.extend([""]*2)
elif len(item)<3:
item.extend([""])
print(item_list)

Append to list from another list

i have list like
list = ['1,2,3,4,5', '6,7,8,9,10']
I have problem with "," in list, because '1,2,3,4,5' its string.
I want to have list2 = ['1','2','3','4'...]
How i can do this?
Should be something like that:
nums = []
for str in list:
nums = nums + [int(n) for n in str.split(',')]
You can loop through and split the strings up.
list = ['1,2,3,4,5', '6,7,8,9,10']
result = []
for s in list:
result += s.split(',')
print(result)
Split each value in the original by , and then keep appending them to a new list.
l = []
for x in ['1,2,3,4,5', '6,7,8,9,10']:
l.extend(y for y in x.split(','))
print(l)
Use itertools.chain.from_iterable with map:
from itertools import chain
lst = ['1,2,3,4,5', '6,7,8,9,10']
print(list(chain.from_iterable(map(lambda x: x.split(','), lst))))
# ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Note that you shouldn't use list name for variables as it's a built-in.
You can also use list comprehension
li = ['1,2,3,4,5', '6,7,8,9,10']
res = [c for s in li for c in s.split(',') ]
print(res)
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list2 = []
list2+=(','.join(list).split(','))
','.join(list) produces a string of '1,2,3,4,5,6,7,8,9,10'
','.join(list).split(',') produces ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
join method is used to joined elements in a list by a delimiter. It returns a string in which the elements of sequence have been joined by ','.
split method is used to split a string into a list by a delimiter. It splits a string into an array of substrings.
# Without using loops
li = ['1,2,3,4,5', '6,7,8,9,10']
p = ",".join(li).split(",")
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Removing duplicated numbers within tuples

For example I want to remove the extra 1s and 2s in this tuple ( '1',
'1',
'1',
'1',
'1',
'1',
'1',
'2',
'2',
'2') to return ('1', '2')
How can I do this?
You can't modify tuple in place, So definitely you have to get new tuple. You can use set to remove duplicate elements.
>>> tp = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
>>> tp = tuple(set(tp))
>>> tp
('1', '2')
As Alok correctly mentions, you have to create a new tuple. As Alok demonstrates, you can of course assign it to the variable that previously held the original tuple.
If you don't care about order, use set as Alok suggests. If you however want to preserve the order (of first occurrence of each unique value), you can use a very similar trick with an OrderedDict:
from collections import OrderedDict
# Different example to demonstrate preserved order
tp = ('2', '2', '2', '1', '1', '1', '1', '1', '1', '1')
tp = tuple(OrderedDict.fromkeys(tp).keys())
# Now, tp == ('2', '1')
They are correct, tuples in python are immutable therefore you cannot update the current tuple. This function loops through data creating a list of indexes that do not currently exist! It then returns a tuple of the list! Good luck!
data = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '3', '4','4')
def removeDoubles(data):
out = []
for i in data:
if i in out:
continue
out.append(i)
del data
return tuple(out)
print removeDoubles(data)
You can do this using a set:
a = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
b = tuple(set(a))
If the order is important you could sort b.

python slice set in list

i would like to slice a set within a list, but every time i do so, i get an empty list in return.
what i try to accomplish (maybe there is an easier way):
i got a list of sets
each set has 5 items
i would like to compare a new set against the list (if the set already exists in the list)
the first and the last item in the set is irrelevant for the comparison, so only the positions 2-4 are valid for the search of already existing sets
here is my code:
result_set = ['1', '2', '3', '4', '5']
result_matrix = []
result_matrix.append(result_set)
slicing the set is no problem:
print result_set[1:4]
['2', '3', '4']
print result_matrix[:][1:4]
[]
i would expect:
[['2', '3', '4']]
I think this is what you want to do:
>>> target_set = ['2', '3', '4']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
True
>>> target_set = ['1', '2', '3']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
False
Generalising and making that a function:
def is_set_in_matrix(target_set, matrix):
return any(True for l in matrix if list(target_set) == l[1:-1])
>>> result_matrix = [['1', '2', '3', '4', '5']]
>>> is_set_in_matrix(['1', '2', '3'], result_matrix)
False
>>> is_set_in_matrix(['2', '3', '4'], result_matrix)
True
# a quirk - it also works with strings...`
>>> s = '234'
>>> is_set_in_matrix(s, result_matrix)
True
Note that I have used l[1:-1] to ignore the first and last elements of the "set" in the comparison. This is more flexible should you ever need sets of different lengths.
>>> result_set = ['1', '2', '3', '4', '5']
>>> print result_set[1:4]
['2', '3', '4']
>>> result_matrix.append(result_set[1:4])
>>> result_matrix
[['2', '3', '4']]
Using result_matrix[:] returns the whole matrix as it is. You need to treat the result you want as a part of the array.
>>> result_matrix.append(result_set)
>>> result_matrix[:]
[['1', '2', '3', '4']]
>>> result_matrix[:][0]
['1', '2', '3', '4']
>>> result_matrix[0][1:4]
['2', '3', '4']
Also, as pointed out by falsetru:
>>> result_matrix.extend(result_set)
>>> result_matrix
['1', '2', '3', '4']
>>> result_matrix[1:4]
['2', '3', '4']

Removing characters from a 2d list

lst = [['1', 'ertt', '9', '8', '', '', '', '\n'], ['1', 'ertt',
'9', '', '32', '6', '0.6', '0.7\n'], ['1', 'ertt',
'9', '8', '', '', '', '\n'], ['1', 'ertt', '9', '', '',
'6.6', '', '\n'], ['1', 'ertt', '9', '', '32', '', '', '1.8\n']]
How can i remove the \n from the last column of each row. i want to keep the numbers but just remove the pesky \n?
You can simply recreate the list with list comprehension, like this
print [item[:-1] + [item[-1].rstrip("\n")] for item in lst]
For every item in lst, we create a new list like this
item[:-1] + [item[-1].rstrip("\n")]
Here item[:-1] means that, everything except the last element and item[-1] means the last element. We simply right strip the \n from that.

Categories