从python列表中获取特定元素的索引

时间:2018-09-27 10:31:59

标签: python arrays list indexing find

我有一个大小不一的列表,如下所示:

[234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231]

“大数字”至少比小数字大10倍。列表中总共有4个“大数字”:1234441222341232311231231

我想找到第三和第四“大数字”的索引:

values: 234 454 123444 123 234 122234 234 354 654 123231 234 342 1231231 indices: 0 1 2 3 4 5 6 7 8 9 10 11 12

如您所见,第3个“大数字”的索引为9,第4个“大数字”的索引为12。因此,输出应为912

5 个答案:

答案 0 :(得分:4)

这里的排序是不好的,因为如果在较小的值long之前出现较大的long值,则该顺序将被破坏,就像在本示例中那样123444 > 123231。而是使用enumerate查找大于其他项目值10倍的项目,然后按其出现顺序将其索引附加到新列表中,然后获取包含索引的新列表的第3和第4项

longs = []
j = min(l)

for idx, item in enumerate(l):
    if item/10 > j:
        longs.append(idx)

print(*longs[2:])

列表理解

longs = [idx for idx, item in enumerate(l) if item/10 > j]
9 12

答案 1 :(得分:-2)

实现此目的的一种方法是在列表中的值中找到拐点。可以通过使用阈值因子来完成此操作。

例如:

def inflection_index(a, threshold=10):
    a.sort()

    current = 0
    for next in range(1, len(a)):
        if a[next] >= threshold * a[current]:
            return i
        current += 1

    return None

更复杂的方法包括找到曲线的凹度根据导数变化的位置。您可以找到有关hereherehere

的更多信息

答案 2 :(得分:-2)

您可以通过以下方式实现此目的:对列表进行排序,然后使用索引的反向切片找到最大值的索引:

num = [234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231]

temp = sorted(num)

for i in temp[::-1][:2]:
    print("Index of", i, "is:", num.index(i))

结果:

Index of 1231231 is: 12
Index of 123444 is: 2

答案 3 :(得分:-2)

list = [234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231]
print (list)
list.sort()
print (list)
my_len = len(list)
print (my_len)
print ("The longest ones are at the end")
print (list[my_len-1])
print (list[my_len-2])
# output
# [234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231]
# [123, 234, 234, 234, 234, 342, 354, 454, 654, 122234, 123231, 123444, 1231231]
# 13
# The longest ones are at the end
# 1231231
# 123444

# Ok how about this 

list = [234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 342, 1231231]
print (list)
my_new_list = []
for idx, val in enumerate(list):
    print(idx, val)
    my_new_list.append((idx,val))
    print(my_new_list)
# output
#[234, 454, 123444, 123, 234, 122234, 234, 354, 654, 123231, 234, 
#342, 1231231]
#0 234
#1 454
#2 123444
#3 123
#4 234
#5 122234
#6 234
#7 354
#8 654
#9 123231
#10 234
#11 342
#12 1231231
#[(0, 234), (1, 454), (2, 123444), (3, 123), (4, 234), (5, 122234), 
#(6, 234), (7, 354), (8, 654), (9, 123231), (10, 234), (11, 342), 
#(12, 1231231)]

答案 4 :(得分:-3)

您可以先对元素进行排序。然后,对于每个最大的元素,在原始列表中找到其索引。 您应该看起来像这样:

add_action('woocommerce_product_options_ebook_product_data', 'wdm_add_ebook_settings');
function wdm_add_ebook_settings()
{
global $woocommerce, $post;

//ebook
echo '<div class="options_group">';
woocommerce_wp_text_input(array(
    'id' => 'e_isbn',
    'label' => __('ISBN del ebook', 'tema'),
    'desc_tip' => 'true',
    'description' => __('ISBN del libro sin guiones', 'tema'),
    'type' => 'text',
));
(... etc)
相关问题