Reputation: 9501
I have the following list
lst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999',]
I need to be able to take the list and then divide the Adams number by lets say 100, and put that new number back into the list and then add it to gregs total.I started by splitting out the list, I am not wanting someone to right the code, I just need a way to separate out each part of the list so I can view it as individual parts.
for i in sod_hng_hhl_lst:
g=i.split(",")
This gives
['Adam','widgets','5769']
etc
what is best way to divided the number and then add it to another group in the list.
Upvotes: 0
Views: 77
Reputation: 20141
Use tuple unpacking this way, if you know there are always 3 items:
name,type,number = i.split(',')
# now name="Adam", type="widgets", number="5769"
In your sample:
for triplet in sod_hng_hhl_lst:
name,type,numberString = triplet.split(",")
# because this is a string and we want a number:
num_as_integer = int(numberString)
# do something with num_as_integer
new_number = num_as_integer * 2
newtriplet = ','.join([name, type, new_number])
However, I would strongly advise using tuples of values rather than strings that are split:
sod_hng_hhl_lst = [ ('Adam', 'widgets', 5769),
#... etc
]
This way the number stays as a number, and you don't have to join and split strings all the time.
for idx,triplet in enumerate(sod_hng_hhl_lst):
name,type,number = triplet
new_number = number * 2
# change just the number in the triplet
sod_hng_hhl_lst[idx][2] = new_number
If people always have unique names, then as mgilson suggests you can use a dictionary:
dct = {"Adam": ('widgets', 5769),
#....
}
Iterating:
for person,details in dct.items():
thing, number = details
new_num = number * 2
dct[person][1] = new_num
Upvotes: 1
Reputation: 309929
It looks to me like a dictionary would be a MUCH better data structure.
splitter = (x.split(',') for x in original_list)
d = { k:[v1,float(v2)] for k,v1,v2 in splitter }
Now you can access the data by the person's name:
assert d['Adam'][1] == 5769
In other words, d['Adam']
will give you the list ['widget',5769]
and from there you can change the number, add it to other peoples numbers, etc.
Upvotes: 1
Reputation: 113975
In [1]: lst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999']
In [2]: lst = [s.split(',') for s in lst]
In [4]: for l in lst:
l[-1] = float(l[-1])
...:
In [5]: for l in lst:
...: if l[0] == "Adam":
...: l[-1] /= 100
...:
In [6]: lst
Out[6]:
[['Adam', 'widgets', 57.69],
['joe', 'balls', 7186.0],
['greg', 'tops', 1819.999]]
Upvotes: 1