简体   繁体   中英

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

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'?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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