This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sorting or Finding Max Value by the second element in a nested list. Python
I've written a program that gives me a list of tuples. I need to grab the tuple with with the max number in the second value.
(840, 32), (841, 3), (842, 4), (843, 4), (844, 6), (845, 6), (846, 12), (847, 6), (848, 10), (849, 4), ..snip...
I need to get back (840,32) because 32 is the highest second number in the tuple. How can I achieve this? I've tried a variety of ways but keep getting stuck here is the complete code:
D = {}
def divisor(n):
global D
L = []
for i in range(1,n+1):
if n % i == 0:
L.append(i)
D[n] = len(L)
for j in range(1001):
divisor(j)
print(D.items())
Use max() with lambda:
In [22]: lis=[(840, 32), (841, 3), (842, 4), (843, 4), (844, 6), (845, 6), (846, 12), (847, 6), (848, 10), (849, 4)]
In [23]: max(lis, key=lambda x:x[1])
Out[23]: (840, 32)
or operator.itemgetter:
In [24]: import operator
In [25]: max(lis, key=operator.itemgetter(1))
Out[25]: (840, 32)
Related
This question already has answers here:
Sort a list of tuples by 2nd item (integer value) [duplicate]
(9 answers)
Closed 1 year ago.
I am currently trying to solve a problem involving lists and sorting (i.e.) when a list (not a normal one ,but a list of tuple ) is entered ; the program should print out the list but in an orderly(increasing order) manner based on the 2nd elements of each tuples.
ex:
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Here is what I have tried until now:
def sorting(L):
le=len(L)
G=[]
Lnew=[list(l) for l in L]
for i in range(le):
G.append(Lnew[i][1])
G.sort()
Lnew.remove(Lnew[i][1]) #where the problem is
for k in range(len(G)):
Lnew[k][1]=G[k]
for elt in Lnew:
tuple(elt)
return L
An error displays "list.remove(x): x not in list" .
how do I proceed in that case? or is there a simpler way to tackle the problem ?
from operator import itemgetter
lista_of_tuples = sorted(list_of_tuples, key_itemgetter(0))
itemgetter parameter can be 0,1,2 depending which one to order it by
def sorting(my_list):
return sorted(my_list, key=lambda x: x[1])
sorting([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])
Output: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
I am trying to get the highest 4 values in a list of tuples and put them into a new list. However, if there are two tuples with the same value I want to take the one with the lowest number.
The list originally looks like this:
[(9, 20), (3, 16), (54, 13), (67, 10), (2, 10)...]
And I want the new list to look like this:
[(9,20), (3,16), (54, 13), (2,10)]
This is my current code any suggestions?
sorted_y = sorted(sorted_x, key=lambda t: t[1], reverse=True)[:5]
sorted_z = []
while n < 4:
n = 0
x = 0
y = 0
if sorted_y[x][y] > sorted_y[x+1][y]:
sorted_z.append(sorted_y[x][y])
print(sorted_z)
print(n)
n = n + 1
elif sorted_y[x][y] == sorted_y[x+1][y]:
a = sorted_y[x]
b = sorted_y[x+1]
if a > b:
sorted_z.append(sorted_y[x+1][y])
else:
sorted_z.append(sorted_y[x][y])
n = n + 1
print(sorted_z)
print(n)
Edit: When talking about lowest value I mean the highest value in the second value of the tuple and then if two second values are the same I want to take the lowest first value of the two.
How about groupby?
from itertools import groupby, islice
from operator import itemgetter
data = [(9, 20), (3, 16), (54, 13), (67, 10), (2, 10)]
pre_sorted = sorted(data, key=itemgetter(1), reverse=True)
result = [sorted(group, key=itemgetter(0))[0] for key, group in islice(groupby(pre_sorted, key=itemgetter(1)), 4)]
print(result)
Output:
[(9, 20), (3, 16), (54, 13), (2, 10)]
Explanation:
This first sorts the data by the second element's value in descending order. groupby then puts them into groups where each tuple in the group has the same value for the second element.
Using islice, we take the top four groups and sort each by the value of the first element in ascending order. Taking the first value of each group, we arrive at our answer.
You can try this :
l = [(9, 20), (3, 16), (54, 13), (67, 10), (2, 10)]
asv = set([i[1] for i in l]) # The set of unique second elements
new_l = [(min([i[0] for i in l if i[1]==k]),k) for k in asv]
OUTPUT :
[(3, 16), (2, 10), (9, 20), (54, 13)]
From the list
l =[(3,4),(2,3),(4,3),(3,2)]
I want to sort out all second appearances of pairs with the same members in reverse order. I.e., the result should be
[(3,4),(2,3)]
What's the most concise way to do that in Python?
Alternatively, one might do it in a more verbose way:
l = [(3,4),(2,3),(4,3),(3,2)]
L = []
omega = set([])
for a,b in l:
key = (min(a,b), max(a,b))
if key in omega:
continue
omega.add(key)
L.append((a,b))
print(L)
If we want to keep only the first tuple of each pair:
l =[(3,4),(2,3),(4,3),(3,2), (3, 3), (5, 6)]
def first_tuples(l):
# We could use a list to keep track of the already seen
# tuples, but checking if they are in a set is faster
already_seen = set()
out = []
for tup in l:
if set(tup) not in already_seen:
out.append(tup)
# As sets can only contain hashables, we use a
# frozenset here
already_seen.add(frozenset(tup))
return out
print(first_tuples(l))
# [(3, 4), (2, 3), (3, 3), (5, 6)]
This ought to do the trick:
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[23]: [(3, 4), (2, 3)]
Expanding the initial list a little bit with different orderings:
l =[(3,4),(2,3),(4,3),(3,2), (1,3), (3,1)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[25]: [(3, 4), (2, 3), (1, 3)]
And, depending on whether each tuple is guaranteed to have an accompanying "sister" reversed tuple, the logic may change in order to keep "singleton" tuples:
l = [(3, 4), (2, 3), (4, 3), (3, 2), (1, 3), (3, 1), (10, 11), (10, 12)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:]) or not any(y[::-1] == x for y in l)]
Out[35]: [(3, 4), (2, 3), (1, 3), (10, 11), (10, 12)]
IMHO, this should be both shorter and clearer than anything posted so far:
my_tuple_list = [(3,4),(2,3),(4,3),(3,2)]
set((left, right) if left < right else (right, left) for left, right in my_tuple_list)
>>> {(2, 3), (3, 4)}
It simply makes a set of all tuples, whose members are exchanged beforehand if first member is > second member.
This question already has an answer here:
Python += with a list and a tuple [duplicate]
(1 answer)
Closed 7 years ago.
<class 'list'>'s insert method helps to add element ((1,2), (3, 4)) in a lst with expected output lst = [((1,2), (3, 4))],
lst = []
lst.insert(0, ((1,2), (3, 4)))
lst.insert(1, ((5, 6), (7, 8)))
But += operator does not give same result(lst = [(1, 2), (3, 4)]).
lst = []
lst += ((1,2), (3, 4))
+= operator internally calls __iadd__ method.
Why __iadd__ does not add element in a way class <'list'>'s insert(index,element) method does ? Because maintaining index needs extra name-value pair in my merge sort code is a big overhead..
x += y, where x and y are list-like will create a new list with the contents of y concatenated to the contents of x.
Since you don't want to append the contents of the tuple ((1,2), (3, 4)) to lst, instead want the tuple added to the list, you should lst.append(((1,2), (3, 4))) instead.
>>> lst = []
>>> lst.append(((1, 2), (3, 4)))
>>> lst.append(((5, 6), (7, 8)))
>>> lst
[((1, 2), (3, 4)), ((5, 6), (7, 8))]
This question already has answers here:
Is there a simple way to delete a list element by value?
(25 answers)
Closed 7 years ago.
How to find and delete only one element in a list in Python?
# Example:deleting only the first (1,2) in the list
a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
# result expected
a = [(4, 5), (7, 5), (1, 2), (5, 2)]
Use the list.remove() method to remove the first occurrence, in-place:
a.remove((1, 2))
Demo:
>>> a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
>>> a.remove((1, 2))
>>> a
[(4, 5), (7, 5), (1, 2), (5, 2)]
See the Mutable Sequence Types documentation:
s.remove(x)
same as del s[s.index(x)]
and s.index() only ever finds the first occurrence.
Hello if you want to delete any thing in lists
use these codes
mylist.pop(element_order) #mylist stands for your list and
#element_order stands for the order of element is the list and if it is the
#first element it will be 0
or you can use
mylist.remove(the_element)
note that in the pop it is a method not a list
mylist.pop(0)
print mylist
dont use
mylist = mylist.pop(0)