Please, if I have a list of tuples, say:
list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
How do I get all the names in ascending order?
How do I get a list that shows the tuples in ascending order of names?
Thanks
CodePudding user response:
If you sort a list of tuples, by default the first item in the tuple is taken as the key. Therefore:
list_ = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
for name, *_ in sorted(list_):
print(name)
Output:
Aaron
Ben
James
Max
Or, if you want the tuples then:
for t in sorted(list_):
print(t)
...which produces:
('Aaron', 24, 1290)
('Ben', 27, 1900)
('James', 27, 2000)
('Max', 23, 2300)
CodePudding user response:
Assuming by ascending you mean alphabetical?
You can do it with sorted
:
a = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
sorted(a, key=lambda x: x[0])
Output:
[('Aaron', 24, 1290),
('Ben', 27, 1900),
('James', 27, 2000),
('Max', 23, 2300)]
CodePudding user response:
lst = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
print(sorted(lst))
Prints
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
CodePudding user response:
list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
sorted_names = sorted([i[0] for i in list])
print(sorted_names)
Output:
['Aaron', 'Ben', 'James', 'Max']
sorted_by_name = sorted(list, key=lambda tup: tup[0])
print(sorted_by_name)
Output:
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
CodePudding user response:
>>> l = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
>>> sorted([name for name, _, _ in l])
['Aaron', 'Ben', 'James', 'Max']
>>> sorted(l)
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
Be advised that list
is an object in Python, so when you create a variable with the name list
, you overwrite that reference and you cannot use list(something)
after in your program.
CodePudding user response:
You can use key
parameter in sort
or sorted
function. Here's an example:
my_list = [('James', 27, 2000), ('Aaron', 24, 1290), ('Max', 23, 2300), ('Ben', 27, 1900)]
my_list_sorted_by_names = sorted(my_list, key=lambda x: x[0])
And the result will be:
[('Aaron', 24, 1290), ('Ben', 27, 1900), ('James', 27, 2000), ('Max', 23, 2300)]
You can use list comprehension to extract names from sorted list:
ordered_names = [i[0] for i in my_list_sorted_by_names]