繁体   English   中英

如何.pop()2D列表上的特定项目?

[英]How to .pop() a specific item on a 2D list?

如何.pop() 2D列表上的特定项目? 假设我有清单:

fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]

如果我.pop() fruit_list ,它将返回['cherry', 'orange', 'strawberry'] ,因为那是列表的最后一项,但是在Python中有一种方法可以只弹出'mango' ,这是最后一项内部清单?

用这个:

item = fruit_list[0].pop()

请参见下面的演示:

>>> fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]
>>> fruit_list[0]
['tomato', 'pineapple', 'mango']
>>> fruit_list[0].pop()
'mango'
>>> fruit_list
[['tomato', 'pineapple'], ['cherry', 'orange', 'strawberry']]
>>>

注意如何首先将fruit_list索引为0以获得内部列表。 然后,您调用.pop

您需要在内部列表上调用.pop()然后:

fruit_list[0].pop()

您的外部fruit_list包含更多列表对象。 如果要从这些列表之一弹出项目,请直接在此列表上调用.pop()

快速演示:

>>> fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]
>>> fruit_list[0]
['tomato', 'pineapple', 'mango']
>>> fruit_list[0].pop()
'mango'
>>> fruit_list
[['tomato', 'pineapple'], ['cherry', 'orange', 'strawberry']]

暂无
暂无

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

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