ordering a list python list of objects [duplicate] - python

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 6 years ago.
I have a list containing Student objects with the following attributes: name, hours and qpoints. The list is stored in the variable data. Why am I getting a None return in the following? In other words, data.sort(key = Student.gpa) returns None, even though there is a method returning the gpa in the Student class. I have imported the Student class in my code.
def choiceInput(data):
choice = input('Enter method of sorting <GPA>, <Name>, or <Credits>: ')
choice = choice[0].lower()
if choice == 'g':
return data.sort(key = Student.gpa)
elif choice == 'n':
return data.sort(key = Student.getName)
else:
return data.sort(key = Student.getpPoints)

sort sorts a list in-place and returns None. If you print data after calling sort you'll find it sorted as you expected.

Related

How to sort list that i get from os.listdir(path) [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 1 year ago.
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
sorted(a), sorts items in same way as seen in a list
a.sort() also sort list in that way. Is it possible that 'suit10.png' and 'suit12.png' go on the end of list?
Use custom sort as follows:
from functools import cmp_to_key
def cmp_items(a, b):
if int(a.split('suit')[1].split('.png')[0]) > int(b.split('suit')[1].split('.png')[0]):
return 1
elif int(a.split('suit')[1].split('.png')[0]) == int(b.split('suit')[1].split('.png')[0]):
return 0
else:
return -1
cmp_key = cmp_to_key(cmp_items)
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
a.sort(key = cmp_key)
print(a)
Both the sorted function and the list.sort method take an optional key argument which dictates how items are to be sorted. Its value is to be a function that takes a member of the list as an argument and returns a value (usually a number). If a and b are elements of the list, then a will be placed before b if func(a) < func(b).
So, in this case, you could do
a.sort(key=lambda x : int(x[4:].split('.')[0]))

Why is this program returning None? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
How can I create a Python custom function to get list of strings having length more than a number n when we pass number n and list of strings?
I tried using this function but it returns None:
lst=['shiva', 'patel', 'ram','krishna', 'bran']
filtered_list=[]
def word_remove(n, lst):
for i in lst:
if len(i)>n:
return filtered_list.append(i)
print(word_remove(4,lst))
The output is :
None
append method on a list does not return any value. Hence the None type.
Append function has no return type. Try instead this.
def word_remove(n, lst):
for i in lst:
if len(i) > n:
filtered_list.append(i)
return filtered_list
lst = ['shiva', 'patel', 'ram','krishna', 'bran']
filtered_list=[]
def word_remove(n, lst):
for i in lst:
if len(i)>n:
filtered_list.append(i)
return filtered_list
print (word_remove(4,lst))
Output:
['shiva', 'patel', 'krishna']
The method append does not return anything. So you need to return the whole filtered_list.

List is not printing in Python [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 3 years ago.
My following code is supposed to collect numeric inputs from the user, put it in a list, and sort them:
def build_list():
"""Builds a list by continually collecting input from the user until 'done' is provided."""
raw_list = []
while True:
item = input("Enter a numeric value: ")
if item.lower() == "done":
break
try:
item = int(item)
except ValueError:
print("That wasn't a valid number. Try again or enter 'done' to stop making the list.")
else:
raw_list.append(item)
return raw_list
def sort_list(unsorted_list):
sorted_list = unsorted_list.sort()
return sorted_list
def main():
my_list = build_list()
my_list = sort_list(my_list)
print(my_list)
if __name__ == '__main__':
main()
This piece of code is printing "None" instead of printing my sorted list. What step am I missing here?
The sort() fonction (as well as the reverse() function) works "in-place" and always return None.
You should write:
def sort_list(unsorted_list):
sorted_list = list(unsorted_list) # local copy if needed
sorted_list.sort()
return sorted_list
You can also use the sorted() function:
def sort_list(unsorted_list):
sorted_list = sorted(unsorted_list)
return sorted_list
See: Sorting HOW TO
sort sorts a list inplace and returns None. Either call sort without returning it:
def main():
my_list = build_list()
my_list.sort() # Here
print(my_list)
or use sorted:
def main():
my_list = build_list()
my_list = sorted(my_list) # Here
print(my_list)

Python3 function not returning complete list [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 4 years ago.
I'm trying to make a function that takes an input list parameter and do some math inside, returning a new list with the data collected from the math, but I'm always getting an empty list as a result. How do I need to pass the list to the function in order to get this to work?
inputArray = [12,6,7,3,8]
def derive (self, *inputArray):
outputarray = []
for i in inputArray:
operatorA = inputArray[i]
operatorB = inputArray[i+1]
if operatorA > operatorB:
operation = operatorA - operatorB
outputarray.append(operation)
else:
operation = operatorB - operatorA
outputarray.append(operation)
print(outputarray)
derive(inputArray)
You were misusing for. To iterate through index, you should use for i in range(len(inputArray) - 1). This will iterate through the list of indexes.
Also, you created a function that requires 2 arguments, but call it with just one, so I removed self.
And to finish, I believe you used the * in an attempt to refer to the string address. That's C/C++ syntax, but won't work on python. Instead, you can return the value to the original string:
inputArray = [12,6,7,3,8]
def derive (inputArray):
outputarray = []
for i in range(len(inputArray)-1):
operatorA = inputArray[i]
operatorB = inputArray[i+1]
if operatorA > operatorB:
operation = operatorA - operatorB
else:
operation = operatorB - operatorA
outputarray.append(operation)
print(outputarray)
return(outputarray)
inputArray = derive(inputArray)

How are these return statements different [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 8 years ago.
Take these two sample code statments:
result = []
return result.append(feed.entries[0])
&
result = []
result.append(feed.entries[0])
return result
The first gives me an error because the method that result is passed to complains of a NonType not being iterable. Why is this? To me both statements are equivalent
The append method of a list does not return anything
>>> a = []
>>> type(a.append(12))
<type 'NoneType'>
So when you're doing:
return result.append(feed.entries[0])
You're actually returning None in all cases, whereas when you do:
result.append(....)
return result
you're returning the list after it has been mutated (modified) hence giving a the expected result.

Categories