3

I have an intro to programming lab using python. I want to split a list:

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

into two new lists:

items_1 = ['40','10','30','4','18','40','76','10']

items_2 = ['40','40','40','5','40','40','80','10']

Any help is appreciated.

jpp
  • 159,742
  • 34
  • 281
  • 339

4 Answers4

2

So here is the standard zip one-liner. It works when items is non-empty.

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

items_1, items_2 = map(list, zip(*(i.split('/') for i in items)))

The map(list(..)) construct can be removed if you are happy with tuples instead of lists.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

I suggest something like this:

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']
items_1 = list()
items_2 = list()

for item in items:
  i_1, i_2 = item.split("/") #Split the item into the two parts
  items_1.append(i_1)
  items_2.append(i_2)

Result (from the IDLE shell)

>>> print(items_1)
['40', '10', '30', '4', '18', '40', '76', '10']
>>> print(items_2)
['40', '40', '40', '5', '40', '40', '80', '10']

It works even when items is empty.

lyxαl
  • 1,108
  • 1
  • 16
  • 26
0

First split the elements of items (explained here), then zip them (explained here):

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

items_tuples = map(lambda x: x.split('/'), items)

items_1, items_2 = zip(*items_tuples)

But note that this will cause a ValueError if you ever call it when items is empty.

0

You can try these methods :

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

print(list(zip(*[i.split('/') for i in items])))

or

print(list(zip(*(map(lambda x:x.split('/'),items)))))

output:

[('40', '10', '30', '4', '18', '40', '76', '10'), ('40', '40', '40', '5', '40', '40', '80', '10')]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88