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)]
Related
I have a list=[1,2,3,4]
And I only want to receive tuple results for like all the positions in a matrix, so it would be
(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)
I've seen several codes that return all the combinations but i don't know how to restrict it only to the tuples or how to add the (1,1),(2,2),(3,3),(4,4)
Thank you in advance.
You just need a double loop. A generator makes it easy to use
lst = [1,2,3,4]
def matrix(lst):
for i in range(len(lst)):
for j in range(len(lst)):
yield lst[i], lst[j]
output = [t for t in matrix(lst)]
print(output)
Output:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
If you just want to do this for making pairs of all symbols in the list
tuple_pairs = [(r,c) for r in lst for c in lst]
If you have instead some maximum row/colum numbers max_row and max_col you could avoid making the lst=[1,2,3,4] and instead;
tuple_pairs = [(r,c) for r in range(1,max_row+1) for c in range(1,max_col+1)]
But that's assuming that the lst's goal was to be = range(1, some_num).
Use itertools.product to get all possible combinations of an iterable object. product is roughly equivalent to nested for-loops with depth specified by the keyword parameter repeat. It returns an iterator.
from itertools import product
lst = [1, 2, 3, 4]
combos = product(lst, repeat=2)
combos = list(combos) # cast to list
print(*combos, sep=' ')
Diagonal terms can be found in a single loop (without any extra imports)
repeat = 2
diagonal = [(i,)*repeat for i in lst]
print(*diagonal sep=' ')
You can do that using list comprehension.
lst=[1,2,3,4]
out=[(i,i) for i in lst]
print(out)
Output:
[(1, 1), (2, 2), (3, 3), (4, 4)]
I want to convert list = [1,4,2,3,0] to list_tup = [(1,4),(4,2),(2,3),(3,0)]. You can see my code below but it outputs [(1,4),(2,3)]. I am wondering how to adjust indices in zip.
list=[1,4,2,3,0]
list_tup = tuple(zip(list[0::2], list[1::2]))
Try zipping the whole list with the list without the first element:
l = [1,4,2,3,0]
print(list(zip(l, l[1:])))
Or use unpack *:
l = [1,4,2,3,0]
print([*zip(l, l[1:])])
They both output:
[(1, 4), (4, 2), (2, 3), (3, 0)]
Try Zipping whole list without first element of the list
l = [1,4,2,3,0]
print(list(zip(l, l[1:])))
output:
[(1, 4), (4, 2), (2, 3), (3, 0)]
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)
I'm new to Python as the screen name attests. I was attempting to sort a list of tuples, think (x,y) pairs in a list and ran into a problem. My goal is to sort the list of tuples by the x variables in ascending order primarily but then sort
I investigated the wiki on HowToSort at http://wiki.python.org/moin/HowTo/Sorting/ and thought I would try the operator module and the itemgetter function as a key.
The simple sorted() function can sort the tuple fine, but when you want one index ascending and one ascending, I'm lost. Here is the code:
from operator import itemgetter, attrgetter
ItemList = [(1,7),(2,1),(1,5),(1,1)]
# Want list sorted with X values descending, then y values ascending
# expected [(2, 1), (1, 1), (1,5), (1, 7)]
print
print ' Input:', ItemList
print 'Output1:',sorted(ItemList, reverse = True)
print
print ' Input:', ItemList
print 'Output2:', sorted(ItemList, key = itemgetter(-0,1))
print
print ' WANTED:', '[(2, 1), (1, 1), (1,5), (1, 7)]'
with the following output:
Input: [(1, 7), (2, 1), (1, 5), (1, 1)]
Output1: [(2, 1), (1, 7), (1, 5), (1, 1)]
Input: [(1, 7), (2, 1), (1, 5), (1, 1)]
Output2: [(1, 1), (1, 5), (1, 7), (2, 1)]
WANTED: [(2, 1), (1, 1), (1, 5), (1, 7)]
I obviously, do not understand the itemgetter function, so any help would be appreciated on that.
Also, any ideas on how to do the two sort on (x,y) pairs? I am hoping to avoid a lambda solution but I'm sure that's where this is going. Thanks.
-0 is the same thing as 0. More-over, negative indices have a different meaning to itemgetter(); it does not mean that the values are negated.
Use a lambda instead:
sorted(ItemList, key=lambda item: (-item[0], item[1]))
Demo:
>>> ItemList = [(1,7),(2,1),(1,5),(1,1)]
>>> sorted(ItemList, key=lambda item: (-item[0], item[1]))
[(2, 1), (1, 1), (1, 5), (1, 7)]
Negative indices take items from the end of a sequence:
>>> end = itemgetter(-1)
>>> end([1, 2, 3])
3
The itemgetter() will never modify the retrieved item, certainly not negate it.
Note that itemgetter() is only a convenience method, you do not have to use it and for more complex sorting orders, a custom function or lambda is the better choice.
From a python list of tuples (which is essentially a cartesian product of a list with itself) I want to delete (a,b) if (b,a) is in the list.Only one of (a,b) or (b,a) must be retained. So a list
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
must reduce to
[(1,2),(1,3),(2,3)]
(Although deleting (1,2) and retaining (2,1) is fine)
I tried doing this but I am not sure about deleting from a list while iterating over it. This doesn't work. (Gives me [(1, 2), (2, 1), (2, 3), (3, 1), (3, 3)])
[pairs.remove((a,b)) for (a,b) in pairs if ((b,a) in pairs)]
Why delete the incorrect ones from the list?
Use itertools.combinations to generate the correct ones instead.
>>> import itertools
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]
>>> [el for el in pairs if el[0] < el[1]]
[(1,2),(1,3),(2,3)]
pairs = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
new_pairs = []
for a, b in pairs:
if (a, b) in new_pairs or (b, a) in new_pairs:
pass
else:
new_pairs += [(a,b)]
new_pairs = [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]