val, idx = min((val, idx) for (idx, val) in enumerate(my_list))
这条语句给出了最小值和该最小值的索引。我很想知道这是如何工作的。
我做了type((value, index) for index, value in enumerate(percent_chance_per_stock) if value > 0)并得到了<class 'generator'>。它如何与min函数结合使用并返回一个元组?
发布于 2021-02-22 23:48:29
下面是不使用generator expression时的分步操作
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 0, 9]
>>> # ^ <- '0' is the smallest num. @8th pos.
>>> # the generator version: saving the tmp_list and faster
>>> val, idx = min((val, idx) for idx, val in enumerate(lst))
>>> print(f' minimum num: {val}, position: {idx} ')
minimum num: 0, position: 8
>>> # now it's more steps for storing the num->idx in the tmp_list first:
>>> tmp_lst = []
>>> for idx, val in enumerate(lst):
tmp_lst.append((val, idx)) # store num, idx but in reverse order
>>> tmp_lst
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7), (0, 8), (9, 9)]
>>> min(tmp_lst) # gives the (nums, idx) It works, since tuple comp. by order
(0, 8)
>>> https://stackoverflow.com/questions/66314704
复制相似问题