I have the lists:
a_list =[['a','1'],['b','2'],['c','3']...]
b_list=['a','b','c']
To access an element that is letters in a_list
we would do a_list[0][0]
However if I try to do this a_list[0:3][0]
I kept getting the same result as a_list[0][0]
. How might I get all three elements of the a_list
.
This is problem because then I can't use the following code:
all(x in [['a','1'],['b','2'],['c','3']] for x in ['a','b','c'])
The list I have is a lot larger so it would be nice if I can represent as a slice like this:
all(x in a_list[0:3][0] for x in ['a','b','c'])
But the list instead represents the index of the slice not the index of the list contained in the list.
Use operator.itemgetter
:
import operator
all(x in map(operator.itemgetter(0), a_list[0:3]) for x in ['a','b','c'])
# True
As per How to efficiently compare two unordered lists (not sets) in Python? , you can use counter
from collections import Counter
Counter(i[0] for i in a_list[:3]) == Counter(b_list)
How about the following? Iterate through the subset of a_list
and test if sub-element 0 is part of b_list
.
all(x[0] in b_list for x in a_list[0:3])
checking the presence of each element of b_list
in a_list
and return True
or Fasle
depends on whether the element is present or not.
a_list =[['a','1'],['b','2'],['c','3']]
b_list=['a','b','c','d']
a_list_1 = list(map(lambda x:x[0],a_list))
result = list(map(lambda a: a in a_list_1, b_list))
"""
output
[True, True, True, False]
"""
Using list-comprehension
:
a_list =[['a','1'],['b','2'],['c','3']]
b_list=['a','b','c']
print(all(x[0] in b_list for x in a_list))
OUTPUT :
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.