[英]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.