简体   繁体   English

从 Python 中的列表中提取子列表

[英]Extract sublist from list in Python

how can I extract for example [['A', '123'], ['A', '456']] from mylist if I filtered by 'A'?如果我按“A”过滤,如何从 mylist 中提取例如 [['A', '123'], ['A', '456']]?

mylist = [['A', '123'],
 ['A', '456'],
 ['B','847'],
 ['B','677']]

I made a code for you.我给你做了一个代码。

mylist = [['A', '123'],
          ['A', '456'],
          ['B', '847'],
          ['B', '677']]

output = [lst for lst in mylist if 'A' in lst]
print(output)

Or you can use this code;或者您可以使用此代码;

output = [lst for lst in mylist if 'A' == lst[0]]

Here are two ways to achieve the results you want.这里有两种方法可以达到你想要的结果。

mylist = [['A', '123'],
 ['A', '456'],
 ['B','847'],
 ['B','677']]
letter = 'A'
# Using list comprehension
print([l for l in mylist if l[0] == letter])
# Using filer function 
print(list(filter(lambda l: l[0] == letter, mylist)))

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

相关问题 在给定条件下从python列表中提取子列表的简短方法 - Short way to extract sublist from list in python by given conditions 从list的子列表中提取最长的字符串。 蟒蛇 - Extract longest strings from sublist within list . Python Python:从给定属性的对象列表中提取子列表的最快方法 - Python: fastest way to extract sublist from a list of objects given an attribute 从 python 列表创建子列表 - create a sublist from a python list 从python中的列表创建子列表 - creating a sublist from a list in python 在python中,如何通过匹配原始列表中的字符串模式从字符串列表中提取子列表 - In python, how do i extract a sublist from a list of strings by matching a string pattern in the original list 如何从列表中提取子列表,其中前一个元素的最后一个字符与最后一个元素的第一个字符相同? - 蟒蛇 - How to extract a sublist from a list where the last character of the previous element is the same as the first character of the last element? - python 从列表python的单个列表中删除子列表 - remove sublist from a single list of list python 从Python中的列表中提取随机子列表 - Extracting a random sublist from a list in Python 从python中的列表列表中选择一个子列表 - select a sublist from a list of lists in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM