简体   繁体   中英

Python: Get item(s) at index list

I am trying to write something that takes a list, and gets the item(s) at an index, either one or multiple.

The example below which I found in another post here works great when I have more than one index. This example doesnt work if b = a single index.

a = [-2,1,5,3,8,5,6]
b = [1,2,5] 
c = [ a[i] for i in b]

How do I get this to work with both 1 and multiple index? Example:

a = [-2,1,5,3,8,5,6]
b = 2 
c = [ a[i] for i in b] doesnt work in this case

You can actually check if the type your trying to use for fetching the indices is a list (or a tuple, etc.). Here it is, wrapped into a function:

def find_values(in_list, ind):
    # ind is a list of numbers
    if isinstance(ind, list):
        return [in_list[i] for i in ind]
    else:
        # ind is a single numer
        return [in_list[ind]]

in_list = [-2,1,5,3,8,5,6]
list_of_indices = [1,2,5]
one_index = 3

print(find_values(in_list, list_of_indices))
print(find_values(in_list, one_index))

The function takes the input list and the indices (renamed for clarity - it's best to avoid single letter names). The indices can either be a list or a single number. If isinstance determines your input is a list, it proceeds with a list comprehension. If it's a number - it just treats it as an index. If it is anything else, the program crashes.

This post gives you more details on isinstance and recognizing other iterables, like tuples, or lists and tuples together.

Instead of creating a list that manually validates the value of list b in the list a, you could create a separate 3 line code to print out the overlapping intersection of list a and b by this:

a = [-2,1,5,3,8,5,6]
b = [3,4,6] 

for i in range(0,len(b)):
    if b[i] in a:
        print(b[i])

By doing so, you would be able to print out the overlapping intersection even if there were 1 or even no value stored in list b.

a = [-2, 1, 5, 3, 8, 5, 6]
a2 = [-2]
b = [1, 2, 5]
b2 = [1]
c = [a[i] for i in b]
c2 = [a2[i-1] for i in b2]

The first item of the list is 0, the list with one item is perfectly valid.

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