How can I resolve this problem?
def common_elements(tuple1, tuple2):
set1 = set(tuple1)
set2 = set(tuple2)
lst1 = list(set1.intersection(set2))
return tuple(lst1.sort()) #TypeError: 'NoneType' object is not iterable
print(common_elements((1, 2, 3, 4), (4, 53, 3, 5, 2, 5, 2, 6, 0)))
list.sort() will sort the list in-place, but the return value is None.
sorted(list) will return a new list object that is sorted.
The correct code should thus be:
def common_elements(tuple1, tuple2):
set1 = set(tuple1)
set2 = set(tuple2)
lst1 = list(set1.intersection(set2))
return tuple(sorted(lst1))
print(common_elements((1, 2, 3, 4), (4, 53, 3, 5, 2, 5, 2, 6, 0)))
sort()
sorts a list in place and returns None
. You need to call sort()
and then return the same list in two different statements:
lst1.sort()
return tuple(lst1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.