TransWikia.com

Splitting values in a list and making variables of them

Stack Overflow Asked by Premier12 on November 22, 2021

I have a list which looks like this:

list1 = ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']

I would like to make 4 variables of a->:100 // b->:100 // c->:50 // d->:90. Something like this:

var1 would be = a->:100 and
var2 would be = b->:100
etc.

my code right now is:

for i in list1:
   z = [x.split(',')[3] for x in list1)
   var1 = z[0]
   var2 = z[1]
   var3 = z[2]
   var4 = z[3]

One Answer

Instead make a dictionary of key value pairs

In [7]: list1
Out[7]: ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']

In [8]: {i.split("->:")[0].strip():i.split("->:")[1].strip() for i in list1[-1].split(",")}
Out[8]: {'a': '100', 'b': '100', 'c': '50', 'd': '90'}

Update: If you want to use variables only then

In [21]: list1 = ['a', '1-1-2020', '100', 'a->:100, b->:100, c->:50, d->:90']
In [23]: list1_split = list1[-1].split(",")
In [32]: var1 = list1_split[0].strip()

In [33]: var2 = list1_split[1].strip()

In [34]: var3 = list1_split[2].strip()

In [35]: var4 = list1_split[3].strip()

In [36]: var1
Out[36]: 'a->:100'

In [37]: var2
Out[37]: 'b->:100'

In [38]: var3
Out[38]: 'c->:50'

In [39]: var4
Out[39]: 'd->:90'

Answered by bigbounty on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP