简体   繁体   中英

Python - NameError: name itemgetter not defined

I just started learning Python came across this very simple code could not get it right:

import operator;

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=itemgetter(1))

I got the error:

NameError: name 'itemgetter' is not defined.

Any idea?

you must import the module like,

import operator

b=[(5,3),(1,3),(1,2),(2,-1),(4,9)]
sorted(b,key=operator.itemgetter(1))

itemgetter而不是operator.itemgetter可以做

from operator import itemgetter

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.

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