Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list indexes into new lists python

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.

like image 667
Lucas Le Doux Avatar asked Dec 06 '25 05:12

Lucas Le Doux


2 Answers

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.

like image 161
jpp Avatar answered Dec 08 '25 17:12

jpp


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.

like image 26
lyxal Avatar answered Dec 08 '25 18:12

lyxal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!