-4

I have the following list of strings:

data = ["1","0","1","<>","0","1","0","<>","1","0","1"]

What I'd like as a result is:

[[1, 0, 1], [0, 1, 0], [1, 0, 1]]

E.g. a list of lists where each list is delimited by <> and the resultant strings converted to integers.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

4 Answers4

3

You can use itertools.groupby to effectively partition at each <>, then take the resulting groups where the key isn't True (eg: it's a <>) and convert to ints, eg:

from itertools import groupby

data = ["1","0","1","<>","0","1","0","<>","1","0","1"]
new_date = [[int(i) for i in g] for k, g in groupby(data, '<>'.__ne__) if k]
# [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

I suggest you more functional-style solution:

data = ["1","0","1","<>","0","1","0","<>","1","0","1"]
reduce(lambda a, b: a[:-1] + [a[-1] + [int(b)]] if b != '<>' else a + [[]], data, [[]])
shybovycha
  • 11,556
  • 6
  • 52
  • 82
0

You may try this also.

l = ["1","0","1","<>","0","1","0","<>","1","0","1"]
m = []
x = []
j = []
for i in l:
    if  i == '<>':
        m.append(x)
        x = []
        j = []
    else:
        x.append(int(i))
        j.append(int(i))
m.append(j)
print(m)

Output:

[[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
-2

You can try using list comprehensions with a combination of joining and splitting:

your_list = [[int(j) for j in i.split()] for i in ' '.join(data).split('<>')]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • That will fail the second the list has a number in it with more than one digit. – Andrew Magee Mar 09 '15 at 10:42
  • How will it differentiate `["1", "0", "<>", ...]` from `["10", "<>", ...]`? – Andrew Magee Mar 09 '15 at 10:44
  • I fixed it now, but the problem seemed to pertain only to ones and zeros. – Malik Brahimi Mar 09 '15 at 10:47
  • This may work, but *boy* is it an ugly approach, and a fragile one at that. – Martijn Pieters Mar 09 '15 at 13:31
  • @MartijnPieters How is it fragile? It works without any possibility of failure. – Malik Brahimi Mar 09 '15 at 16:05
  • It only works for input data that itself doesn't contain your chosen delimiter. You already had a sequence, why join then split again? You'd have to keep adjusting this approach for different inputs based on what data is contained. The `groupby` solution is far more robust in that it doesn't have to first destroy the input sequence. Also, your approach is very inefficient for large inputs; building a huge string then splitting it up is just a waste of memory and cycles. – Martijn Pieters Mar 09 '15 at 16:11