1

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.

Juan Ramos
  • 179
  • 1
  • 10

5 Answers5

2

Use operator.itemgetter:

import operator

all(x in map(operator.itemgetter(0), a_list[0:3]) for x in ['a','b','c'])
# True
Chris
  • 29,127
  • 3
  • 28
  • 51
1

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)
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

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])
normanius
  • 8,629
  • 7
  • 53
  • 83
0

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]

"""
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

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
DirtyBit
  • 16,613
  • 4
  • 34
  • 55