itertools groupby-python中未显示任何值
我正在尝试使用python-itertools groupby-python中未显示任何值,python,group-by,itertools,Python,Group By,Itertools,我正在尝试使用python-itertools.groupby对字符串中的值进行分组。我已尝试使用此代码: for key,values in itertools.groupby(s): print(key,list(values)) 我得到这个输出: a ['a'] b ['b'] a ['a', 'a'] b ['b', 'b', 'b'] c ['c'] a [] b [] a [] b [] c [] 这很好。但是当我添加if条件并以这种方式将代码更改为: out = ''
itertools.groupby
对字符串中的值进行分组。我已尝试使用此代码:
for key,values in itertools.groupby(s):
print(key,list(values))
我得到这个输出:
a ['a']
b ['b']
a ['a', 'a']
b ['b', 'b', 'b']
c ['c']
a []
b []
a []
b []
c []
这很好。但是当我添加if
条件并以这种方式将代码更改为:
out = ''
for key,values in itertools.groupby(s):
if len(list(values))==1:
out+=key
else:
out += key
out += str(len(list(values)))
print(key,list(values))
我得到这个输出:
a ['a']
b ['b']
a ['a', 'a']
b ['b', 'b', 'b']
c ['c']
a []
b []
a []
b []
c []
我不知道为什么列表是空的
值
是一个迭代器,在用完之前只能对其调用一次list()
。您应该将该结果保存在变量中并重用它
out = ''
for key,values in itertools.groupby(s):
value_list = list(values) # values iterator exhausted here, can't use it again
if len(value_list)==1:
out+=key
else:
out += key
out += str(len(value_list))
print(key,value_list)
因为您在这里使用了迭代器:
len(list(values))
对不起,我没有得到它@胡安帕·阿里维拉加