简体   繁体   中英

Can I return a single element of a list, as a list?

I have list that I want to return a specific element from, but maintain it as a list, ie,:

inventory = ['aaa', 'bbb', 'ccc']
target = 'bbb' #may or may not be set
if target: inventory = inventory[1]
for i in inventory:
    #do something with 'bbb'

This obviously pseudo but demonstrates the general flow; fwiw, I've written it this way so that a user can specify a specific entry, or all entries, but not two and not 0. Currently if I specify a target , then the for loop iterates over each character, rather than the single element.

To answer your question directly, the following will do it:

inventory = [inventory[1]]

This creates a single-element list consisting of the first element of inventory , and assigns it back to inventory . For example:

>>> inventory = ['aaa', 'bbb', 'ccc']
>>> inventory
['aaa', 'bbb', 'ccc']
>>> inventory = [inventory[1]]
>>> inventory
['bbb']

An arguably cleaner way is to use a list comprehension to select elements of inventory that match the given criterion:

>>> inventory = ['aaa', 'bbb', 'ccc']
>>> target = 'bbb'
>>> inventory = [item for item in inventory if (not target) or (item == target)]
>>> inventory
['bbb']

You can simply use a list literal if you're only interested in using this for your iteration:

for i in [inventory]:
    ...

But I doubt you'll ever need a for loop for a singleton iterable.

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