简体   繁体   中英

Pythonic way to find value in 2D list?

With numpy array, you can check a specific column with slicing, ie array[:, 0] . For a list, checking whether a 2D element is inside is as simple as ["one", "two"] in some_list . However, just looking if "one" is present requires one to iterate through the elements, ie ["one" == item[0] for item in some_list] .

I largely prefer numpy array except that my array needs to be modified (adding at the end and removing values). I like to work with list because they are very simple to work with. I am considering dataframe but I feel like I should be able to find some clever and efficient way to this kind of operation using a list.

To check whether item exists at any position in a 2D list list_of_lists , you can do

any(item in sublist for sublist in list_of_lists)

Note, unlike the list-flattening idea of another answer, this solution doesn't require any extra memory to be used.

Not sure if this is what you're asking, but if all you want is to know if an element exists inside a list of lists l , you can flatten l and use the operator in as below:

>> l = [["one", "two"], ["three", "four"]]
>> one_is_in_l = "one" in [item for sublist in l for item in sublist]
>> print(one_is_in_l)
True

You can also use numpy just to do the check with:

>> l = [["one", "two"], ["three", "four"]
>> one_is_in_l = "one" in np.array(l)
>> print(one_is_in_l)
True

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