[英]Python - Sorting Through List With A Line Code
I want to sort a list according to my specification with a single line of code instead of 2 lines of code, i can assign variable names in a for loop as shown in the sample code but i can't sort using a for loop 我想根据规范用单行代码而不是2行代码对列表进行排序,我可以在for循环中分配变量名称,如示例代码所示,但我无法使用for循环进行排序
my current code works fine but i have to zip 2 lists (new, new2) to finally be able to sort, anyway way to just do it in a single line of code to get 'symbol' and 'priceChange'? 我当前的代码工作正常,但我必须压缩2个列表(new,new2)才能最终进行排序,无论如何,只需在一行代码中进行操作即可获得“ symbol”和“ priceChange”?
sample = [{'symbol': 'APPL', 'priceChange': '-5.916', 'bidPrice': '0.03201500'},
{'symbol': 'URZ', 'priceChange': '2.916', 'bidPrice': '0.03201500'}]
stock = ['APPL']
new = [i['priceChange'] for i in sample if i['symbol'] in stock]
new2 = [i['symbol'] for i in sample if i['symbol'] in stock]
result = list(zip(new2, new))
print(result)
为什么不这样
new = [[i['priceChange'],i['symbol']] for i in sample if i['symbol'] in stock]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.