Reputation: 13
I have a list that consists of this:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254.0, 239.0, 224.0, 717.0],
['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 248.0, 224.0, 205.0, 677.0]]
I wish for the first three floats to be merged together like this:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254239224, 717.0],
['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 24822205, 677.0]]
I need to leave the final float as its own element. The three floats need to change data type to int (to remove the decimal place) and then they need to be merged together as one element. I am having great trouble as to how I can do this.
e.g.
254.0, 239.0, 224.0 --> 254239224
Upvotes: 0
Views: 501
Reputation: 609
You may use map and lambda for this operation
map(lambda x: x[:-4]+[int(''.join(map(str, (map(int, x[-4:-1])))))]+[x[-1]], list_of_lists)
output:
[['Esté', 'Double', 'Medium', ' £10 ', '0.5', nan, nan, nan, 254239224, 717.0],['Esté', 'Double', 'Medium', ' £10 ', '1.0', nan, nan, nan, 24822205, 677.0]]
Upvotes: 0
Reputation: 3787
You need to iterate through your input to get each list. From there, use list slicing to get the n-4 to n-1 elements to merge and make as a part of your list!
Since those elements are floats and you want the output as a string ignoring the decimals, you can use lambda to iterate over every element in each[-4:-1]
eg. [254.0, 239.0, 224.0]
, convert that to int and then to string. ['254', '239', '224.0']
with be the result. And to merge them, use str.join()
! And then, insert the merged result to the right position of your list!
That is,
print [each[:-4]+[''.join(map(lambda x:str(int(x)),each[-4:-1]))]+[each[-1]] for each in r]
Upvotes: 0
Reputation: 1884
To join these floats 254.0, 239.0, 224.0 --> 254239224
for l in list_of_lists:
floats = l[index_of_first_float:index_of_last_float+1]
concat = ''.join([str(int(f)) for f in floats])
...
Upvotes: 0
Reputation: 77860
I'll divide this into three steps for easier understanding; you can make this a single-line derivation.
slice = src[-4:-1] # This grabs the three items
big_str = ''.join([str(int(x)) for x in slice])
big_int = int(big_str)
After this, just plaster your original item back together:
src = src[:-4] + [big_int] + src[-1]
Does that get you moving?
Upvotes: 1