2

I have written a code that takes a string from a file and splits it into a list. But i need to split the strings into lists that are nested.

 ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

 ['Acer', 'Beko', 'Cemex', 'Datsun', 'Equifax', 'Gerdau', 'Haribo']

this is the output, and i am trying to figure out how to take the numerical data from the first list and append it to the name list in order to create the nested returned list below. any ideas would be fantastic

[['Acer' 481242.74], ['Beko' 966071.86], ['Cemex' 187242.16], ['Datsun' 748502.91], ['Equifax' 146517.59], ['Gerdau' 898579.89], ['Haribo' 265333.85]]

1 Answer 1

2

With list comprehension:

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = [[x.split()[0], float(x.split()[1])] for x in the_list]

print final_list

Without list comprehension:

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = list()

for item in the_list:
    name = item.split()[0]
    amount = float(item.split()[1])
    final_list.append([name, amount])

print final_list

Output:

[['Acer', 481242.74], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.