我有一个包含不同数据类型(例如数字和字符串)的列表:
foo = [5,2,'a',8,4,'b','y',9, 'd','e','g']
假设我要在列表中找到所有连续的字符串,并将它们分组在一起:
bar = [ ['a'],['b','y'],['d','e','g'] ]
我该怎么做
答案 0 :(得分:3)
这是使用groupby
的绝好机会:
from itertools import groupby
foo = [5,2,'a',8,4,'b','y',9, 'd','e','g']
bar = [list(g) for k, g in groupby(foo, key=lambda x: isinstance(x, str)) if k]
产生所需的:
[['a'], ['b', 'y'], ['d', 'e', 'g']]
答案 1 :(得分:0)
遍历列表中的每个元素(如果类型为str
,则将其附加到one_d_array
,否则,将one_d_array
附加到two_d_array
,前提是{{1 }}不为空。每当元素不是one_d_array
类型的元素时,请重置one_d_array
str
答案 2 :(得分:0)
无需使用任何导入,就可以通过迭代列表元素的良好的“ for循环”来完成此操作。这是一个适用于您想要的任何类型的代码,不仅适用于字符串:
def group_list(a_list, a_type):
res = []
sublist = []
for elem in a_list:
if isinstance(elem, a_type):
# Here the element is of type a_type: append it to a sublist
sublist.append(elem)
else:
# Here the element is not of type a_type: append the sublist (if not empty) to the result list
if sublist:
res.append(sublist)
sublist = []
# If the last element of the list is of type a_type, the last sublist has not been appended: append it now
if sublist:
res.append(sublist)
return res
foo = [5,2,'a',8,4,'b','y',9, 'd','e','g']
print(group_list(foo,str))
# [['a'], ['b', 'y'], ['d', 'e', 'g']]