3

I have this list of strings:

x = ['+27', '05', '1995 F']

I want some code that outputs this:

['+', '27', '05', '1995', 'F']

I was thinking about using the .split() function on the last element so I wrote this code:

x=['+27', '05', '1995 F']
x[2]=x[2].split()

This outputs:

['+27', '05', ['1995', 'F']]

How do ensure the 2nd element is not a sub-list, and instead output this?

['+27', '05','1995','F']

Should I use insert and del?

I wrote this for the first element using insert and del:

x=x.split("/")
x.insert(0,x[0][0])
x.insert(1,x[1][1:])
del x[2]

This outputs:

['+', '27', '05', '1995 F']

Is there a better way?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 6
    I fixed a __lot__ of capitalization, indentation, spelling and formatting errors in your post. Please take a bit more effort for future questions to keep quality high. – orlp Apr 28 '15 at 04:36

4 Answers4

5

Here's a solution using 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']

This works by splitting each string in x into groups of characters based on whether they're digits or not, then joining those groups back into strings, and finally stripping whitespace from the resulting strings.

As you can see, unlike the other solutions presented so far, it splits '+27' into '+' and '27' (as your question says you want).

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
1
x = ['+27', '05', '1995 F']
l = []
[l.extend(e.split()) for e in x]
print l

and checkout this for the fancier one Flatten (an irregular) list of lists

Community
  • 1
  • 1
Dyno Fu
  • 8,753
  • 4
  • 39
  • 64
1

Here is one quick solution:

x=['+27', '05', '1995 F']
finlist=[]
for element in x:
    for val in element.split(" "):
        finlist.append(val)
print finlist

Or:

x=['+27', '05', '1995 F']
finlist=[]
for element in x:
    finlist.extend(element.split(" "))
print finlist
1

"How do ensure the 2nd element is not a sub-list output this?" Use extend for that:

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']
fixxxer
  • 15,568
  • 15
  • 58
  • 76