How can I delete a specific cell using .remove() in python - python

Say I have a list that looks like this
f = [['person','place','item'],['george','home','phone']]
how would I search through that list and delete a specific cell using f.remove()
I have tried:
f.remove('item')
which should remove 'item' but instead it returns the error
Exception has occurred: ValueError
list.remove(x): x not in list

you have list of lists, if you want to remove item from 1st list, you should do the following way:
f[0].remove('item')
.remove() is inplace operation and doesn't return any value. i.e it will change the list itself, so after above operation your list will be:
print(f)
# output [['person', 'place'], ['george', 'home', 'phone']]
for second list:
f[1].remove('home')

You can use list comprehension to do this. You need to put the if statement inside the inner loop.
f = [['person','place','item'],['george','home','phone']]
f = [[a for a in x if a != 'item'] for x in f]
The output of this will be:
[['person', 'place'], ['george', 'home', 'phone']]
This is equivalent to:
f = [['person','place','item'],['george','home','phone']]
new_f = []
for x in f:
temp_list = []
for a in x:
if a != 'item':
temp_list.append(a)
new_f.append(temp_list)
print (new_f)
The output of both will be the same.

Have you tried this?
f[0].remove('item')

You can do it easily using list comprehension
f=[x.remove('item') if 'item' in x else x for x in f]

In your example f is a two-dimensional list, so all the items in f are also lists, and item is not one of them. Depending on your use case, I can see multiple ways of interpreting "remove":
If you want your resulting list to be [['person','place'],['george','home','phone']], you can use
f[0].remove('item')
If you want your resulting list to be [['person','place'],['george','home']] (i.e. removing the whole "column" from the 2D list), then you should first find the index you want to remove, and then use del based on the index:
index = f[0].index('item')
for row in f:
del row[index]

Related

Find Numbers in a List Consisting of Strings and Convert them to Floats

I'm trying to do an exercise where I have a list:
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
And I have to make a second list out of it that looks like this:
list_2 = [['chocolate', 1.20], ['book', 5.50], ['hat', 3.25]]
In the second list the numbers have to be floats and without the ' '
So far I've come up with this code:
for item in list_1:
list_2.append(item.split(';'))
The output looks about right:
[['chocolate', '1.20'], ['book', '5.50'], ['hat', '3.25']]
But how do I convert those numbers into floats and remove the double quotes?
I tried:
for item in list_2:
if(item.isdigit()):
item = float(item)
Getting:
AttributeError: 'list' object has no attribute 'isdigit'
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [x.split(';') for x in list_1]
list_3 = [[x[0], float(x[1])] for x in list_2]
item is a list like ['chocolate', '1.20']. You should be calling isdigit() on item[1], not item. But isdigit() isn't true when the string contains ., so that won't work anyway.
Put the split string in a variable, then call float() on the second element.
for item in list_1:
words = item.split(';')
words[1] = float(words[1])
list_2.append(words)
I don't know if this helpful for you.
But,I think using function is better than just using simple for loop
Just try it.
def list_map(string_val,float_val):
return [string_val,float_val]
def string_spliter(list_1):
string_form=[]
float_form=[]
for string in list_1:
str_val,float_val=string.split(";")
string_form.append(str_val)
float_form.append(float_val)
return string_form,float_form
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
string_form,float_form=string_spliter(list_1)
float_form=list(map(float,float_form))
output=list(map(list_map,string_form,float_form))
print(output)
Your way of creating list_2 is fine. To then make your new list, you can use final_list = [[i[0], float(i[1])] for i in list_2]
You could also do it in the for loop like this:
for item in list_1:
split_item = item.split(';')
list_2.append([split_item[0], float(split_item[1])])
This can be achieved in two lines of code using list comprehensions.
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [[a, float(b)] for x in list_1 for a, b in [x.split(';', 1)]]
The second "dimension" to the list comprehension generates a list with a single sublist. This lets us essentially save the result of splitting each item and then bind those two items to a and b to make using them cleaner that having to specify indexes.
Note: by calling split with a second argument of 1 we ensure the string is only split at most once.
You can use a function map to convert each value.
def modify_element(el):
name, value = el.split(';')
return [name, float(value)]
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
result = list(map(modify_element, list_1))
For a problem like this you can initialize two variables for the result of calling the split function and then append a list of both values and call the builtin float function on the second value.
array = []
for i in a_list:
string, number = i.split(";")
array.append([string, float(number)])
print(array)

Why does this function to convert all items in a list to strings not work?

I have a two dimensional array and I try to convert all items within each array to strings.
First I tried to use a function to_str and this approach didn't work. I do not understand why it doesn't work (it returns the input unchanged):
lst = [['test1', 555], ['test2', 3333]]
def to_str(item):
for i in item:
if not isinstance(i, str):
i = str(i)
return item
output = list(map(lambda item:to_str(item), lst))
output: [['test1', 555], ['test2', 3333]]
Then I used a list comprehension instead, and it worked:
output = list(map(lambda item: [str(i) for i in item], lst))
output: [['test1', '555'], ['test2', '3333']]
Why does the first approach using to_str not work?
You're trying to modify the iteration variable named i. This has no effect at all, you're just rewriting the value of a local variable that points to a list element, but not changing the list itself. For this to work you have to modify the list elements at each index position, something like this:
def to_str(item):
# iterate over the indexes in the item
for i in range(len(item)):
# we can remove this check, and simply convert everything to str
if not isinstance(item[i], str):
item[i] = str(item[i])
return item
Or we can create a new list with the results, instead of overwriting the original (but this will be equivalent to using a list comprehension, better use a list comprehension):
def to_str(item):
result = []
for element in item:
# we can remove this check, and simply convert everything to str
if not isinstance(element, str):
result.append(str(element))
else:
result.append(element)
return result
Also, regarding your second approach: it'd be better if you avoid using list, map and lambda, if what you want is to create a new list as a result use a list comprehension directly. This is a more idiomatic way to solve the problem, also removing the unnecessary string check:
[[str(i) for i in item] for item in lst]
=> [['test1', '555'], ['test2', '3333']]
Converted value i is not used anywhere in approach #1 and function just returns input
def to_str(item):
result = []
for i in item:
if not isinstance(i, str):
i = str(i)
result.append(i)
return result

How to convert a list made up of one tuple into a two item list?

I have a function that returns a one item list, like so:
list = [('array_1','array_2')]
I want to change this so that the list is instead a two item one, without the parentheses or single quotes:
list = [array_1,array_2]
What would be the best way to go about doing this?
Try this
lists = [('array_1','array_2')]
print([y for x in lists for y in x])
output
['array_1', 'array_2']
Use chain.from_iterable
from itertools import chain
list(chain.from_iterable([('array_1','array_2')]))
['array_1', 'array_2']
You can try this:
lst_tuple = [('array_1', 'array_2')]
lst = []
for i in lst_tuple[0]:
lst.append(i)
By iteratating over the list that contains the tuple and appending each item to a new list, you can get this result:
['array_1', 'array_2']
You could just typecast like this.
list = list([('array_1','array_2')][0])

isolating a sub list from a big list in python

I have a big list in python like this small example:
small example:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV', 'MDHTEGSPAEEPPAHAPSPGKFGERPPPKRLTREAMRNYLKERGDQTVLILHAKVAQKSYGNEKRFFCPPPCVYLMGSGWKKKKEQMERDGCSEQESQPCAFIGIGNSDQEMQQLNLEGKNYCTAKTLYISDSDKRKHFMLSVKMFYGNSDDIGVFLSKRIKVISKPSKKKQSLKNADLCIASGTKVALFNRLRSQTVSTRYLHVEGGNFHASSQQWGAFFIHLLDDDESEGEEFTVRDGYIHYGQTVKLVCSVTGMALPRLIIRKVDKQTALLDADDPVSQLHKCAFYLKDTERMYLCLSQERIIQFQATPCPKEPNKEMINDGASWTIISTDKAEYTFYEGMGPVLAPVTPVPVVESLQLNGGGDVAMLELTGQNFTPNLRVWFGDVEAETMYRCGESMLCVVPDISAFREGWRWVRQPVQVPVTLVRNDGIIYSTSLTFTYTPEPGPRPHCSAAGAILRANSSQVPPNESNTNSEGSYTNASTNSTSVTSSTATVVS']
in the file there are many items and each item is a sequence of characters. I want to make a new list in which every item has only one W. the expected output for the small example would be like the expected output.
expected output:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV']
I am trying to do that in python and wrote the following code:
newlist = []
for item in mylist:
for c in item:
if c == W:
newlist.append(item)
but it does not return what I want. do you know how to fix it?
Use .count
Ex:
res = []
mylist = ['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV', 'MDHTEGSPAEEPPAHAPSPGKFGERPPPKRLTREAMRNYLKERGDQTVLILHAKVAQKSYGNEKRFFCPPPCVYLMGSGWKKKKEQMERDGCSEQESQPCAFIGIGNSDQEMQQLNLEGKNYCTAKTLYISDSDKRKHFMLSVKMFYGNSDDIGVFLSKRIKVISKPSKKKQSLKNADLCIASGTKVALFNRLRSQTVSTRYLHVEGGNFHASSQQWGAFFIHLLDDDESEGEEFTVRDGYIHYGQTVKLVCSVTGMALPRLIIRKVDKQTALLDADDPVSQLHKCAFYLKDTERMYLCLSQERIIQFQATPCPKEPNKEMINDGASWTIISTDKAEYTFYEGMGPVLAPVTPVPVVESLQLNGGGDVAMLELTGQNFTPNLRVWFGDVEAETMYRCGESMLCVVPDISAFREGWRWVRQPVQVPVTLVRNDGIIYSTSLTFTYTPEPGPRPHCSAAGAILRANSSQVPPNESNTNSEGSYTNASTNSTSVTSSTATVVS']
for item in mylist:
if item.count("W") == 1:
res.append(item)
print(res)
or
res = [item for item in mylist if item.count("W") == 1]
Output:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV']
The problem is you are iterating each character in each string and appending when a condition is met. Moreover, your logic can't "undo" a list.append operation if another W is found. So if W is met twice in a string, you are appending twice.
Instead, you can use a list comprehension with list.count:
res = [i for i in L if i.count('W') == 1]

Get inner-most elements from triple nested list Python

I have list
players = [[['QB1',7000,20],['RB1',4500,12],['RB2',3800,11]],
[['QB1',7000,20],['RB2',3800,11],['RB1',4500,12]]]
How do I get the first element of each inner-most lists ('QB1', 'RB1' and 'RB2' from the first "secondary," if you will, list) to check if they are the same, however disordered labels as those in another secondary list (they are in this case as both secondary lists contain 'QB1', 'RB1' and 'RB2')?
EDIT:
My desired out is [['QB1','RB1','RB2'],['QB1','RB2','RB1']]. I want to have some way of identifying that these are, for my purpose, the same list.
You can do this:
output = [[i[0] for i in a] for a in players]
The output will be like this:
[['QB1', 'RB1', 'RB2'], ['QB1', 'RB2', 'RB1']]
you can use recursive search for that and get first element of each list or whole list
players = [[['QB1',7000,20],['RB1',4500,12],['RB2',3800,11]],[['QB1',7000,20],['RB2',3800,11],['RB1',4500,12]]]
def retrive_first(lst):
for item in lst:
if type(item) == list:
retrive_first(item)
else:
print "returning ---> ", lst[0]
return lst[0]
print retrive_first(players)
You could also try this:
from operator import itemgetter
[list(map(itemgetter(0), player)) for player in players]
do:
print(list(zip(players))[0])
Or:
print([i[0] for i in players])

Categories

Resources