在python2.7中,下面的代码使用字典fd
(在此示例中表示单词及其计数的频率分布),并将其分成两个列表的列表:[[键], [值]]:
sortedDKandVs = [zip(*sorted(fd.items(), key=itemgetter(1), reverse=True))] #[word,word,...],[count,count]
我可以做,例如:
keys = sortedDKandVs[0]
values = sortedDKandVs[1]
这在Python3中不再有用,我想知道如何转换代码。
这里的答案How to unzip a list of tuples into individual lists?都不再有效,因为在Python3中,zip对象返回迭代器而不是列表,但我不知道如何转换答案。
答案 0 :(得分:6)
Python 2:
Python 2.7.6 (default, Apr 9 2014, 11:48:52)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> di={'word1':22, 'word2':45, 'word3':66}
>>> zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
[('word3', 'word2', 'word1'), (66, 45, 22)]
>>> k,v=zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
>>> k
('word3', 'word2', 'word1')
>>> v
(66, 45, 22)
Python 3:
Python 3.4.1 (default, May 19 2014, 13:10:29)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> di={'word1':22, 'word2':45, 'word3':66}
>>> k,v=zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
>>> k
('word3', 'word2', 'word1')
>>> v
(66, 45, 22)
Python 2和Python 3完全相同
如果你想要列表与元组(Python 3和Python 2):
>>> k,v=map(list, zip(*sorted(di.items(), key=itemgetter(1), reverse=True)))
>>> k
['word3', 'word2', 'word1']
>>> v
[66, 45, 22]