简体   繁体   English

如何解决 TypeError: 'NoneType' object is not iterable in pyhton

[英]how can I solve TypeError: 'NoneType' object is not iterable in pyhton

import pyfiglet
pyfiglet.print_figlet("Niko CyMax",'puffy')

num_list=[ (1,2) , (3,1000) , (5,6) , (9,10) , (8,500) , (70,400) ]

num_list_manual_sort=num_list.sort()
num_list_pro_sort=num_list.sort(key = lambda x: x[1])

for i in num_list_manual_sort:
    print(i)

for i in num_list_pro_sort:
    print(i)

and error is:错误是:

TypeError: 'NoneType' object is not iterable

Sorting a list with sort() changes the list in place , that means, the list num_list is changed directly, instead of the sorted list being returned and the original one left intact.使用sort()对列表进行排序会更改原地列表,这意味着列表num_list会直接更改,而不是返回排序后的列表而原始列表保持不变。 You want to use the builtin sorted function, which does exactly what you want:您想使用内置的sorted function,这正是您想要的:

import pyfiglet
pyfiglet.print_figlet("Niko CyMax",'puffy')

num_list=[(1, 2), (3, 1000), (5, 6), (9, 10), (8, 500), (70, 400)]

num_list_manual_sort = sorted(num_list)
num_list_pro_sort = sorted(num_list, key=lambda x: x[1])

for i in num_list_manual_sort:
    print(i)

for i in num_list_pro_sort:
    print(i)

When you are sorting a list with sort method, you are changing the list itself, and None is returned.当您使用sort方法对列表进行排序时,您正在更改列表本身,并且返回None

num_list_manual_sort=num_list.sort()
num_list_pro_sort=num_list.sort(key = lambda x: x[1])

Both num_list_manual_sort and num_list_pro_sort will hold None . num_list_manual_sortnum_list_pro_sort都将持有None In case you want to get the list back, you can replace it by:如果您想取回列表,可以将其替换为:

num_list.sort()
num_list_manual_sort = num_list[:]
num_list.sort(key = lambda x: x[1])
num_list_pro_sort = num_list[:]

There are more options for doing that, depends on your need.这样做有更多选择,取决于您的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM