简体   繁体   English

尝试对同时包含字符串和浮点数的列表进行排序

[英]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.我尝试制作 2 个列表,一个包含所有重量,一个包含化学符号。 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.这样我就可以对包含权重的列表进行排序,但我真的不知道如何将 2 组合成一个列表。 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
``

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)

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: Append 使用split()或其他一些解析方法将每个元素放入列表中(您可以将它们存储为对象,它们自己的列表等),然后使用 lambda 进行排序,在排序操作期间调用并提供值的 function排序:

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.通过这种方式,您可以获得一个 arrays 数组,其中包含作为字符串的元素数据。 Therefore, because they are strings, when you sort you will need to transform them into numeric values using float() .因此,因为它们是字符串,所以当您排序时,您需要使用float()将它们转换为数值。

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

Another option, read the file and sort it with weight as the key to array of strings ( lines )另一种选择,读取文件并使用权重作为字符串数组( lines )的键对其进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM