mlist = [["Rachel", -50],["Mawer", -50],["Sheen",-50],["Shaheen",51]]
list1 = []
x = sorted(mlist, key = lambda x : x[1])
print(x[1])
x = [x for x in x if x[x][1] != x[0][1]]
print(x)
def over1():
for i in range(4):
if x[i][1] == x[0][1]:
list1.append(x[i][0])
list1.sort()
print(*list1, sep="\n")
over1()
I am trying to delete all variables which have minimum of the second element of each value in the list and I wanted to make it happen with using x
. (print(x)
for control purposes)
In the line x = [x for x in x if x[x][1] != x[0][1]]
compiler gives me the error "list indices must be integers or slices, not list".
Is it possible with using x
only and where is my mistake?
CodePudding user response:
I'm not sure if a complete one-liner would be considered good programming, but I managed to do this in 2 lines by using list comprehension. I first find the minimum value and then use that to produce a resultant list that does not contain the minimum value:
mlist = [['Rachel', -50], ['Mawer', -50], ['Sheen', -50], ['Shaheen', 51]]
min_val = min([a[1] for a in mlist])
x = [a for a in mlist if a[1] != min_val]
print(*x, sep='\n')
Output:
['Shaheen', 51]
CodePudding user response:
x = [x for x in x if x[x][1] != x[0][1]]
First of: this code line is a little hard to read. Second: you're basically trying to iterste over an a list of x, and then assign value of x[0] to it in
for x in x
Third: you iterating over list of lists, so you cant use x[x] because x is equal to ["Rachel": -50]. Fourth: python is interpreter, not compiler, you may want to keep that in mind for later learning of the language