tryhhaaards
tryhhaaards

Reputation: 9

Trying to sort a list with both strings and floats

I have a file containing the elements and their weight and it looks like this:

Ac 227.0
Ag 107.868
Al 26.98154
and so on

My mission is to read all the information from the file in to a program and make a list sorted after the weight of the elements. So I want hydrogen first and its corresponding weight and after hydrogen comes helium with its correspondning weight and so on. I have tried making 2 lists, one containing all the weights and one containing the chemical symbol. That way I can sort the list containing the weights but I dont really know how to combine the 2 into one list after that. Any help is helpful.

Heres the code pretty much:

def create_lists():
    atomic_file = open('atomer2.txt', 'r')
    symbol_list = []
    weight_list = []
    for line in atomic_file:
        symbol_list.append(line.split()[0])
        weight_list.append(line.split()[1])
        wight_list.sort
    atomic_file.close()
    return symbol_list, weight_list
``

Upvotes: 1

Views: 74

Answers (3)

Thy
Thy

Reputation: 478

Another option, read the file and sort it with weight as the key to array of strings (lines)

with open('atomer2.txt', 'r') as fd:
    lines = sorted(fd.readlines(), key=lambda x: float(x.split(" ")[1]))

Upvotes: 1

phoenixinwater
phoenixinwater

Reputation: 340

You're close. Append each element into a list using split() or some other parsing method (you could store them as objects, their own lists, etc.) and then sort using a lambda, a function that is called during the sort operation and provides the value to be sorted with:

elements = []

for line in atomic_file:
    elements.append(s.split())
    
elements.sort(key=lambda x: float(x[1]))

This way you get an array of arrays which contain the element data as strings. Therefore, because they are strings, when you sort you will need to transform them into numeric values using float().

print(elements)    
# [['Al', '26.98154'], ['Ag', '107.868'], ['Ac', '227.0']]

Upvotes: 1

nokla
nokla

Reputation: 1590

You can create a list that every element in it contains the name of the element in its weight, and then sort it by the weight like so:

st = """Ac 227.0
Al 26.98154
Ag 107.868"""

lst = [(line.split(' ')[0], float(line.split(' ')[1])) for line in st.split('\n')]
lst.sort(key=lambda x:x[1])
print(lst)

Upvotes: 1

Related Questions