将列表中的每个字符串拆分为数字和非数字部分
Split each string in a list into digit and non-digit parts
我有这个字符串列表:
x = ['+27', '05', '1995 F']
我想要一些输出这个的代码:
['+', '27', '05', '1995', 'F']
我考虑在最后一个元素上使用 .split()
函数,所以我写了这段代码:
x=['+27', '05', '1995 F']
x[2]=x[2].split()
这输出:
['+27', '05', ['1995', 'F']]
如何确保第二个元素不是子列表,而是输出这个?
['+27', '05','1995','F']
我应该使用 insert
和 del
吗?
我使用 insert
和 del
:
为第一个元素写了这个
x=x.split("/")
x.insert(0,x[0][0])
x.insert(1,x[1][1:])
del x[2]
这输出:
['+', '27', '05', '1995 F']
有没有更好的方法?
x = ['+27', '05', '1995 F']
l = []
[l.extend(e.split()) for e in x]
print l
并检查这个以获得更高级的 Flatten (an irregular) list of lists
这是一个快速解决方案:
x=['+27', '05', '1995 F']
finlist=[]
for element in x:
for val in element.split(" "):
finlist.append(val)
print finlist
或者:
x=['+27', '05', '1995 F']
finlist=[]
for element in x:
finlist.extend(element.split(" "))
print finlist
"How do ensure the 2nd element is not a sub-list output this?"
为此使用 extend
:
In [32]: result = []
In [34]: inp = ['+27', '05', '1995 F']
In [35]: [result.extend(i.split()) for i in inp]
Out[35]: [None, None, None]
In [36]: result
Out[36]: ['+27', '05', '1995', 'F']
这是一个使用 itertools.groupby()
and str.isdigit()
in a list comprehension 的解决方案:
>>> from itertools import groupby
>>> x=['+27', '05', '1995 F']
>>> [''.join(g).strip() for s in x for k, g in groupby(s, str.isdigit)]
['+', '27', '05', '1995', 'F']
它的工作原理是根据字符是否为数字将 x
中的每个字符串分成字符组,然后将这些组连接回字符串,最后从结果字符串中去除空格。
如您所见,与目前介绍的其他解决方案不同,它将“+27”拆分为“+”和“27”(如您的问题所述)。
我有这个字符串列表:
x = ['+27', '05', '1995 F']
我想要一些输出这个的代码:
['+', '27', '05', '1995', 'F']
我考虑在最后一个元素上使用 .split()
函数,所以我写了这段代码:
x=['+27', '05', '1995 F']
x[2]=x[2].split()
这输出:
['+27', '05', ['1995', 'F']]
如何确保第二个元素不是子列表,而是输出这个?
['+27', '05','1995','F']
我应该使用 insert
和 del
吗?
我使用 insert
和 del
:
x=x.split("/")
x.insert(0,x[0][0])
x.insert(1,x[1][1:])
del x[2]
这输出:
['+', '27', '05', '1995 F']
有没有更好的方法?
x = ['+27', '05', '1995 F']
l = []
[l.extend(e.split()) for e in x]
print l
并检查这个以获得更高级的 Flatten (an irregular) list of lists
这是一个快速解决方案:
x=['+27', '05', '1995 F']
finlist=[]
for element in x:
for val in element.split(" "):
finlist.append(val)
print finlist
或者:
x=['+27', '05', '1995 F']
finlist=[]
for element in x:
finlist.extend(element.split(" "))
print finlist
"How do ensure the 2nd element is not a sub-list output this?"
为此使用 extend
:
In [32]: result = []
In [34]: inp = ['+27', '05', '1995 F']
In [35]: [result.extend(i.split()) for i in inp]
Out[35]: [None, None, None]
In [36]: result
Out[36]: ['+27', '05', '1995', 'F']
这是一个使用 itertools.groupby()
and str.isdigit()
in a list comprehension 的解决方案:
>>> from itertools import groupby
>>> x=['+27', '05', '1995 F']
>>> [''.join(g).strip() for s in x for k, g in groupby(s, str.isdigit)]
['+', '27', '05', '1995', 'F']
它的工作原理是根据字符是否为数字将 x
中的每个字符串分成字符组,然后将这些组连接回字符串,最后从结果字符串中去除空格。
如您所见,与目前介绍的其他解决方案不同,它将“+27”拆分为“+”和“27”(如您的问题所述)。