[英]Is there a str.split equivalent for lists in Python?
If I have a string, I can split it up around whitespace with the str.split
method: 如果我有一个字符串,我可以使用
str.split
方法将其拆分为空白:
"hello world!".split()
returns 回报
['hello', 'world!']
If I have a list like 如果我有一个像这样的列表
['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]
Is there a split method that will split around None
and give me 是否存在一种拆分方法,它将拆分为
None
并给我
[['hey', 1], [2.0, 'string', 'another string'], [3.0]]
If there is no built-in method, what would be the most Pythonic/elegant way to do it? 如果没有内置方法,最好的Pythonic /优雅方法是什么?
A concise solution can be produced using itertools: 使用itertools可以生成简洁的解决方案:
groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
if k:
groups.append(list(g))
import itertools.groupby
,然后:
list(list(g) for k,g in groupby(inputList, lambda x: x!=None) if k)
There is not a built-in way to do this. 没有内置的方法来做到这一点。 Here's one possible implementation:
这是一个可能的实现:
def split_list_by_none(a_list):
result = []
current_set = []
for item in a_list:
if item is None:
result.append(current_set)
current_set = []
else:
current_set.append(item)
result.append(current_set)
return result
# Practicality beats purity
final = []
row = []
for el in the_list:
if el is None:
if row:
final.append(row)
row = []
continue
row.append(el)
def splitNone(toSplit:[]):
try:
first = toSplit.index(None)
yield toSplit[:first]
for x in splitNone(toSplit[first+1:]):
yield x
except ValueError:
yield toSplit
>>> list(splitNone(['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]))
[['hey', 1], [2.0, 'string', 'another string'], [3.0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.