Python按最小值排序列表

2024-06-06 22:52:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按最低/最低价格(30美元)排序,价格不断更新。该列表包含其他信息,如unix时间戳等。。所以我唯一能确定价格的方法就是通过一个循环。你知道吗

new = [[1548006540000, '30.48000000', '30.50000000', '30.48000000', '30.49000000', '9.44678000', 1548006599999, '288.05801500', 5, '4.24009000', '129.27641360', '0'], 
[1548006600000, '30.50000000', '30.50000000', '30.48000000', '30.49000000', '8.56304000', 1548006659999, '261.12404810', 3, '8.17304000', '249.23684810', '0'], 
[1548006660000, '30.49000000', '30.49000000', '30.48000000', '30.48000000', '14.27839000', 1548006719999, '435.27885450', 7, '14.27547000', '435.18985290', '0'], 
[1548006720000, '30.50000000', '30.57000000', '30.50000000', '30.53000000', '103.97541000', 1548006779999, '3173.52545900', 28, '58.78941000', '1794.71718910', '0'], 
[1548006780000, '30.53000000', '30.59000000', '30.51000000', '30.52000000', '86.32365000', 1548006839999, '2635.32247120', 31, '23.33218000', '712.42226920', '0'], 
[1548006840000, '30.52000000', '30.52000000', '30.38000000', '30.39000000', '618.95322000', 1548006899999, '18842.24179880', 120, '115.54521000', '3516.61937340', '0'], 
[1548006900000, '30.39000000', '30.39000000', '30.36000000', '30.36000000', '62.09526000', 1548006959999, '1885.52106400', 9, '0.00000000', '0.00000000', '0']]



lowest = []

for l in new:
    sts = ','.join(str(e) for e in l)
    splis = sts.split('\n')
    for lin in splis:
        lan = lin.split(',')
        price = lan[3]



        lowest.append(float(price))

        print(lowest)

因为一个列表中有7个列表,所以我得到了7个循环,最后一个循环 是我需要的信息,但我不能在循环发生时使用min()函数,如何获得最后一个循环的最小值?还有别的方法吗(lambda)?先谢谢你。。你知道吗

澄清一下,价格在每个子列表的第4个索引中。其他人不是。你知道吗


Tags: 方法in信息列表newfor排序价格
3条回答

我已编辑了您的原始代码:

lowest = []

for l in new:
    price = l[3] # get the fourth element from each sublist (index = 3)
    lowest.append(float(price))

min_price = min(lowest) # get the minimum
sorted_list = sorted(lowest) # get the sorted list

取子列表中的第三个值

prices= [i[3] for i in new]
>>> prices
['30.48000000', '30.48000000', '30.48000000', '30.50000000', '30.51000000', '30.38000000', '30.36000000']

还是这个?我很不明白你想要什么

从子列表中的1-4个值中取出最小值

prices = [min(i[1:5]) for i in new]
>>> flat_list
['30.48000000', '30.48000000', '30.48000000', '30.50000000', '30.51000000', '30.38000000', '30.36000000']

我猜这个数据集是经典的市场api,它在给定的时间范围内有第三个值作为最小价格值,对吗?如果是这样的话,两种解决方案都是等价的,但第一种解决方案的速度更快

你应该用lambda。我不知道哪个指数是价格,但如果它总是在指数3中,例如,比你需要的:

lowest = min(new, key=lambda x:x[3])

这将给出第三个元素最小的行。 如果我误解了你,请评论,我会尽力帮助你。你知道吗

相关问题 更多 >