Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python itemgetter打印空列表而不是字符串_Python_Python 2.7 - Fatal编程技术网

Python itemgetter打印空列表而不是字符串

Python itemgetter打印空列表而不是字符串,python,python-2.7,Python,Python 2.7,为什么itemgetter返回空列表而不是相应的字符串 预期输出: from itertools import groupby from operator import itemgetter distance_list = [('Brahmadatta Devadatta', 0.12844036697247707, '2, 6', '0, 10'), ('Brahmadatta Devadatta', 0.07339449541284404, '2, 6',

为什么itemgetter返回空列表而不是相应的字符串

预期输出:

from itertools import groupby
from operator import itemgetter

distance_list = [('Brahmadatta Devadatta', 0.12844036697247707, '2, 6', '0, 10'),
                 ('Brahmadatta Devadatta', 0.07339449541284404, '2, 6', '1, 9'),
                 ('Brahmadatta Sujata', 0.11009174311926606, '2, 6', '4, 8')]

for key, value in groupby(sorted(distance_list), key=itemgetter(0)):
    print map(itemgetter(1), value) #works for printing float numbers
    print map(itemgetter(2), value) # returns an empty list
生成的输出:

2, 6
2, 6
2, 6

我明白了,
['2,6','2,6']['2,6']
你确定-我同意@EngineRefeedId,你碰巧同时打开了这两个地图
value
不是一个列表,而是一个grouper对象,因此您只能在其中迭代一次。如果您希望多个迭代都能工作,请添加
value=list(value)
。因为如果您保留前一行,它会耗尽迭代。您的OP有点误导,因为它注释掉了第一行…;)但这是有道理的——按照@DSM的建议去做,你会没事的
[ ]  
[ ]  
[ ]