繁体   English   中英

这是通过考虑 python 中相应列表的元素从列表中选择某个索引的合理方法吗?

[英]Is this a reasonable way for choosing a certain index from a list by considering the elements of a corresponding list in python?

我对编程比较陌生,并且遇到了这个问题:

有两个列表: C=[i,i,k,l,i] 和 D =[m,n,o,p,q]

我想 select C 的最小元素的索引。 如果 k 或 l 是最小值,这很简单,因为 min function 将直接返回所需的索引。 但如果 i 是最小值,则有几种可能性。 在这种情况下,我想查看列表 D 的元素,但仅查看 i 在 C 中出现的索引。 然后我想根据 D 中那些特定元素的最小值来选择我广受欢迎的索引

我想到了以下代码:

min_C = min(C)
if C.count(min_C) == 1:
    soughtafter_index = C.index(min_C)
else:
    possible_D_value = []
    for iterate in C:
        if iterate==min_C:
            possible_index = C.index(iterate)
            possible_D_value.append(D[possible_index])
     best_D_value = min(possible_D_value)
     soughtafter_index = D.index(best_D_value)

(注意问题中 C 和 D 将始终具有相同的长度)

我还没有机会测试代码,但想问一下是否合理? 有没有更好的方法来处理这个? (如果有第三个列表怎么办——那么这段代码会变得更长……)

谢谢你们

尝试这个:

soughtafter_index = list(zip(C, D)).index(min(zip(C,D)))

更新所需的解释:

>>> C = [1, 5, 1, 3, 1, 4]
>>> D = [0, 1, 1, 3, 0, 1]
>>> list(zip(C, D))
[(1, 0), (5, 1), (1, 1), (3, 3), (1, 0), (4, 1)]
>>> min(zip(C, D))
(1, 0)

暂无
暂无

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

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