简体   繁体   English

我可以返回列表的单个元素作为列表吗?

[英]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. 首先,我以这种方式编写了代码,以便用户可以指定一个特定的条目或所有条目,但不能指定两个而不是0。当前,如果我指定了target ,则for循环遍历每个字符,而不是单个字符元件。

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 . 这产生以下组成的第一个元素的单元素列表inventory ,并给它分配回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元素:

>>> 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. 但是我怀疑您是否需要for单循环可迭代的for循环。

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

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