[英]Finding elements from list in lists embedded in list (Python)
Is there any simple function to iterate through lists embedded in a list in Python?是否有任何简单的 function 可以遍历嵌入在 Python 列表中的列表? I have a list
我有一个清单
A = ["apple", "banana", "cherry"]
. A = ["apple", "banana", "cherry"]
。
Then, I want check which elements could be found in list of lists然后,我想检查哪些元素可以在列表列表中找到
B = [["banana", "cherry", "pear"], ["banana"," orange']]
. B = [["banana", "cherry", "pear"], ["banana"," orange']]
。
The result should be sth like this: c = [["banana", "cherry"], ["banana"]]
.结果应该是这样的:
c = [["banana", "cherry"], ["banana"]]
。
Thanks for your help.谢谢你的帮助。
You can do this with a list comprehension:您可以通过列表理解来做到这一点:
[
[ b
for b in l # loop over items in the sub list
if b in A] # Check in they are in the main list
for l in B # Loop over the big list
]
This will maintain correct order, and also preserve empty lists这将保持正确的顺序,并保留空列表
You can loop over list B and do a set intersection and retain results if there is a match.您可以遍历列表 B 并进行集合交集,如果匹配则保留结果。 Note that set will disrupt the order of items.
请注意,set 会打乱项目的顺序。
C = []
for item in B:
common = set(item).intersection(A)
if len(common) > 0:
C.append(list(common))
print(C) # [['banana', 'cherry'], ['banana']]
Iteration in given lists A & B doable sth like this;给定列表 A 和 B 中的迭代可以这样做;
A = ["apple", "banana", "cherry"]
B = [["banana", "cherry", "pear"], ["banana","orange"]]
C = []
for i in B:
C_temp = []
for j in A:
if j in i:
C_temp.append(j)
C.append(C_temp)
print(C)
Output of C; C 的 Output;
[['banana', 'cherry'], ['banana']]
Here is using map
, lambda
, set
, and list
function to iterate through lists:这里使用
map
、 lambda
、 set
和list
function 来遍历列表:
A = ["apple", "banana", "cherry"]
B = [["banana", "cherry", "pear"], ["banana",'orange']]
C = list(map(lambda c: sorted(list(set(A).intersection(c))), B))
# [['banana', 'cherry'], ['banana']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.